+ 1
How did the elements of the list change?
a = [1,2,3,5,8] for a[1] in a: pass print(a) Output: [1, 8, 3, 5, 8]
4 Answers
+ 8
It modifies because you are taking a[1] as temp variable in loop for iterations. So values executed like
a[1]=1
a[1]=2
a[1]=3
a[1]=5
a[1]=8 so this stays after loop but before all are ovverriden. List value at position at 1 is changes.
See a[] is a list reference variable. Not a not normal temp variable. So it modifies original list.
Generally, loop variable does not exist after loop, local to loop. But in python for loop variables exist after loop also. Looks like, It's scope is function level. Weird result.
+ 5
Each iteration, list value is stored in a[1] .
so a[1]=1, a[1]=2, a[1]=3, a[1]=5, a[1]=8
Only last value is retained. List is modified to
[1,8,3,5,8]
+ 1
Jayakrishna🇮🇳 , why did the list modified?
+ 1
never use this code!!! it's nonsense to use such variable as temp variable for a loop.