0

Can someone explain why value of x and y not same?

# Python code a = [1,2,3,4,1] for x in a: print(x) print("\n") for y in a: print(y) a[y] = 0 # output 1 2 3 4 1 1 0 3 0 1

6th Oct 2021, 3:11 PM
Sushil 🛡️
Sushil 🛡️ - avatar
6 odpowiedzi
+ 1
For x you can directly understand that, there it iterates over list and prints element now for y you are replacing element after printing. First a[1] = 0(as y is 1 for the first iteration) this changes index one element to 0 so you can understand for every element
6th Oct 2021, 3:39 PM
Prabhas Koya
+ 1
You tagged three languages: python, c++, java. Only one is relevant.
6th Oct 2021, 3:31 PM
Simon Sauter
Simon Sauter - avatar
+ 1
The reason why the output is different is that you change a inside the second loop.
6th Oct 2021, 3:33 PM
Simon Sauter
Simon Sauter - avatar
0
Get rid of the irrelevant tags.
6th Oct 2021, 3:13 PM
Simon Sauter
Simon Sauter - avatar
0
Simon Sauter which tag? Code is running without error.
6th Oct 2021, 3:27 PM
Sushil 🛡️
Sushil 🛡️ - avatar
0
Got the answer. Changing the list inside loop and iterating over same list. Due to which list next index data of the iterating list is getting modified.
9th Oct 2021, 10:39 AM
Sushil 🛡️
Sushil 🛡️ - avatar