+ 2

Struked in a question.Someone can explain what happen here.

a=[0,1,2,3] for a[-1] in a: print(a[-1]) Output seems to be 0 1 2 2

28th Oct 2019, 10:29 AM
Mohamed Ishad
Mohamed Ishad - avatar
4 Answers
+ 9
In each iteration, the last item of 'a', i.e. a[-1] is copied with values from 'a' iterable. So we have different 'a' in each iteration. If we want to see 'a' in each step we'll have: 1. [0,1,2,0] => a [-1]=0 2. [0,1,2,1] => a [-1]=1 3. [0,1,2,2] => a [-1]=2 4. [0,1,2,2] => a [-1]=2
28th Oct 2019, 11:01 AM
Qasem
+ 5
Qasem Shouldn't the fourth iteration be [0,1,2,3] as 3 is in a and hence a[-1] as 3
2nd Jan 2020, 10:35 AM
Ozair Khan
Ozair Khan - avatar
+ 5
Qasem Thanks!! Got it.
2nd Jan 2020, 11:04 AM
Ozair Khan
Ozair Khan - avatar
+ 2
Ozair Khan 3 is not in A. It is replaced with 0 at the first iteration and doesn't exist anymore.
2nd Jan 2020, 10:45 AM
Qasem