0
Help please, Why does this instruction list have a reverse effect?
newList = [] for n in range(4): newList.insert(0,n + 0) print (newList)
2 odpowiedzi
+ 2
Hi Jenkins!
It's inserting each element as first element of newList(indices start from 0) in each iteration(0,1,2,3). Inorder to understand this code clearly, you can print the output inside loop.
This is what I mentioned above
newList = []
for n in range(4):
newList.insert(0,n )
print (newList)
+ 1
Jenkins I checked your profile and you have not completed python for begineers course even 1% so first learn it and then try to practice it !
syntax : list.insert(index, element)
The insert() function inserts the given element at the specified index. (index starts from 0 )
you are adding each element to the 0th index so others elements will be shifted to right side.
newList=[]
for n in range(4):
newList.insert(0,n) #n+0 = n
1st iteration --> [0]
2nd iteration --> [1,0]
# 1 is inserted at index 0th so first element is sifted to right side
3rd iteration ---> [2,1,0]
4th iteration ---> [3,2,1,0]
that's why you are getting reversed elements of list
⏺️ Solution 1 :
you can simply use append() function to insert element at the end of list.
newList=[]
for n in range(4):
newList.append(n)
print(newList)
------------------------------------
OR
⏺️Solution 2 : using insert() itself
newList=[]
for n in range(4):
newList.insert(n,n)
print(newList)
#Hope this helps !