Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loops and iterating through lists

Tags:

Here is a snippet of code which gives the output: 0 1 2 2. I had expected the output 3 3 3 3 since a[-1] accesses the number 3 in the list. The explanation given online says "The value of a[-1] changes in each iteration" but I don't quite understand how or why. Any explanations would be great!

a = [0, 1, 2, 3] for a[-1] in a:     print(a[-1]) 
like image 493
kat Avatar asked Jan 09 '16 15:01

kat


1 Answers

While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1].

You can see the loop like these instructions:

a[-1] = a[0] # a = [0, 1, 2, 0] print(a[-1]) # 0 a[-1] = a[1] # a = [0, 1, 2, 1] print(a[-1]) # 1 a[-1] = a[2] # a = [0, 1, 2, 2] print(a[-1]) # 2 a[-1] = a[3] # a = [0, 1, 2, 2] print(a[-1]) # 2 

So, when you are on the third element, then 2 is stored to a[-1] (which value is 1, but was 0 before and 3 on start).

Finally, when it comes to the last element (and the end of the iteration), the last value stored into a[-1] is 2 which explains why it is printed twice.

like image 198
Delgan Avatar answered Oct 05 '22 16:10

Delgan