+ 3

Why is the output 312405 and not 452031?

x = [4,5,2,0,3,1] for i in x: print(x[i],end=" ")

22nd Mar 2022, 1:37 AM
Lenoname
10 Answers
+ 6
Remove the x and keep the i But why because you was indexing it
22nd Mar 2022, 1:42 AM
Ion Kare
Ion Kare - avatar
+ 5
Because in each iteration i takes one of the values in the list. So you're printing: x[4] x[5] x[2] x[0] x[3] x[1]
22nd Mar 2022, 1:44 AM
Simon Sauter
Simon Sauter - avatar
+ 5
If you want to print the numbers in the order they have in the list use print(i) instead of print(x[i]).
22nd Mar 2022, 1:45 AM
Simon Sauter
Simon Sauter - avatar
+ 5
Eliminate x altogether for i in [4,5,2,0,3,1]: print (i,end=" ")
22nd Mar 2022, 2:50 AM
BroFar
BroFar - avatar
+ 4
Index x[i] = 4 so 0,1,2,3,4 which is 3
22nd Mar 2022, 1:42 AM
Ion Kare
Ion Kare - avatar
+ 3
Maybe you mean x = [4,5,2,0,3,1] for i in range(len(x)): print(x[i],end=" ")
22nd Mar 2022, 9:55 AM
Simba
Simba - avatar
+ 2
# Just write like this x = [4,5,2,0,3,1] for i in x: print(i, end='') # When you need a separate list item, you can do this print(i[2])
22nd Mar 2022, 6:59 AM
CodeStory
CodeStory - avatar
+ 2
k = ['a','b','c','d','e','f'] for index, str in enumerate(k): print(index,str)
23rd Mar 2022, 1:51 PM
CodeStory
CodeStory - avatar
0
Uh
22nd Mar 2022, 1:41 AM
Ion Kare
Ion Kare - avatar
0
It wasn't for i in range(value ) It is i in x that means that i will enumerate the list and take the values of the list x from beginning to end : x[i] in first iteration i=first element of the list so x[i]=x[4]=3 2 nd iteration : X[i]=x[5]=1 3rd iteration : X[i]=x[2]=2 Iteration n:4 X[i]=x[0]=4 Iteration n:5 X[i]=x[3]=0 And last iteration : X[i]=x[1]=5 So output will be:312405
23rd Mar 2022, 6:55 PM
ElChapo