How did the elements of the list change? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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]

18th Dec 2022, 10:29 AM
Shantanu
Shantanu - avatar
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.
18th Dec 2022, 10:46 AM
Jayakrishna 🇮🇳
+ 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]
18th Dec 2022, 10:36 AM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 , why did the list modified?
18th Dec 2022, 10:38 AM
Shantanu
Shantanu - avatar
+ 1
never use this code!!! it's nonsense to use such variable as temp variable for a loop.
18th Dec 2022, 1:37 PM
Huawei Smart
Huawei Smart - avatar