x=[1,2,3,4,5]
for x[2] in x:
print(x[2])
print(x)
Output:
1
2
2
4
5
[1, 2, 5, 4, 5]
can somebody throw some light on what is happening here and how is the list changed?
x=[1,2,3,4,5]
for x[2] in x:
print(x[2])
print(x)
Output:
1
2
2
4
5
[1, 2, 5, 4, 5]
can somebody throw some light on what is happening here and how is the list changed?
You are implicitly telling python to do this:
for x_element in x:
x[2] = x_element
print(x[2])
print(x)
because in the for loop you are assigning to x[2]
the iterated element.
Hence, when you get to index 2
, you just assigned to x[2]
the previous value (x[1]
, which is 2
). And when you end the loop X[2]
was assigned x[4]
, that is 5
, in the last iteration.
But please, do not use this code!