+ 1

Can someone simply explain what effect does ‘len’ have in this code output please

nums = [1, 2, 3] for i in range (len(nums)): nums.insert(i,i+2) print(nums)

28th Sep 2021, 3:24 PM
Jenkins
4 odpowiedzi
+ 6
len() function returns the size of any itterible data type. So here len(nums) would return 3 as the size of nums has 3 elements. So this code uses len() to go through every element of the nums list.
28th Sep 2021, 3:28 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
You can just use append() method instead of insert() method like : nums.append(i+2) edit: Jenkins nums = [1, 2, 3] for i in range(len(nums)): nums.append(i+2) print(nums)
28th Sep 2021, 3:39 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 Got it, thanx bro!
28th Sep 2021, 4:05 PM
Jenkins
0
nums = [1, 2, 3] for i in range (len(nums)): nums.insert(i,i+2) print(nums) What would I do if i wanted the output to be [1, 2, 3, 2, 3, 4,] without chnaging the value in the nums list?
28th Sep 2021, 3:33 PM
Jenkins