0

python: strange behavior for: for a[1] in a

dear all why does the following code https://code.sololearn.com/cQ1moerH5kmb/#py change the value of the a[1] element with each iteration? of course this leaves it then with a[1]-element equal to the last element in the list. but why would it reassign the value in the first place? was this discussed in the tutorial? i might have missed it. Best regards

14th May 2020, 8:08 PM
cedi
cedi - avatar
3 Réponses
+ 3
It wasn't discussed in the tutorial I also came to know about it reading from other answers on simliar questions like this https://www.sololearn.com/Discuss/2293183/?ref=app
14th May 2020, 8:12 PM
Abhay
Abhay - avatar
+ 3
cedi in your code a is defined as an list and then a[1] iteration is done over whole list so by this way the value of a[1] which is second element of the list will change for each iteration with the list value till the whole list is traversed. a=[1,2,3,4] for a[1] in a: pass print (a) At initial stage 1 2 3 4 1st iteration 1 1 3 4 2nd iteration 1 2 3 4 3rd iteration 1 3 3 4 4th iteration 1 4 3 4 The list is traversed so Final output is [1 4 3 4]
14th May 2020, 8:15 PM
DishaAhuja
DishaAhuja - avatar
+ 2
In loop, your taking each value into a[1] so it changing.. And it retains last value..
14th May 2020, 8:14 PM
Jayakrishna 🇮🇳