Shouldn't this code print out the items in my list instead of what its printing out | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Shouldn't this code print out the items in my list instead of what its printing out

a=[1,2,3,4,1] for n in a: print(n)

13th Dec 2018, 8:33 AM
Sotomi Oluwadmilola
5 Answers
+ 4
Here n will iterate through each element in the list, Starting from index 0 upto index 4 step 1)element at index 0 in [1,2,3,4,1] is 1 therefore n=1 a[n]=0 i.e. a[1] = 0 so now the list becomes [1,0,3,4,1] print(n) will print 1 step 2)element at index 1 in [1,0,3,4,1] is 0 therefore n=0 a[n]=0 i.e. a[0] = 0 so new list is [0,0,3,4,1] print(n) will print 0 step 3)element at index 2 in [0,0,3,4,1] is 3 therefore n=3 a[n]=0 i.e. a[3] =0 so new list is [0,0,3,0,1] print(n) will print 3 step 4)element at index 3 in [0,0,3,0,1] is 0 therefore n=0 a[n]=0 i.e. a[0]=0 so new list is [0,0,3,0,1] print(n) will print 0 step 5)element at index 4 in [0,0,3,0,1] is 1 therefore n=1 a[n]=0 i.e. a[1]=0 so new list is [0,0,3,0,1] print(n) will print 1
13th Dec 2018, 12:50 PM
Rishi Anand
Rishi Anand - avatar
+ 3
It should. What is it printing out instead?
13th Dec 2018, 8:49 AM
HonFu
HonFu - avatar
+ 2
Sotomi Oluwadmilola, you can not leave out a line of code and expect the output to be the same! How could anybody give a reasonable answer to your original post?
13th Dec 2018, 12:53 PM
HonFu
HonFu - avatar
0
a=[1,2,3,4,1] for n in a: a[n]=0 print(n) Output = 1 0 3 0 1 That is the full code. Line three was missing. But shouldn't the output still be items in my list??
13th Dec 2018, 10:30 AM
Sotomi Oluwadmilola
0
HonFu Sorry typo error
13th Dec 2018, 1:37 PM
Sotomi Oluwadmilola