Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how list actually works in python using for-loop?

I tried this code, I don't understand how it works

a=[1,'a',2,'b','test','exam']
for a[-1] in a:
    print(a[-1])

output

1
a
2
b
test
test
like image 902
Nandish Patel Avatar asked Dec 23 '22 09:12

Nandish Patel


1 Answers

In python you can access the last element of a list implicitly by using the index -1. So a[-1] will return the value of the last element of the list a.

By doing the for loop for a[-1] in a, you iterate through the list, and store the value of the next element of a in its last element.

So to better understand what's going on, you should print the whole list at every iteration, so you can visualize the operation:

a=[1, 'a', 2, 'b', 'test', 'exam']
for a[-1] in a:
    print(a)

You will get:

[1, 'a', 2, 'b', 'test', 1]
[1, 'a', 2, 'b', 'test', 'a']
[1, 'a', 2, 'b', 'test', 2]
[1, 'a', 2, 'b', 'test', 'b']
[1, 'a', 2, 'b', 'test', 'test']
[1, 'a', 2, 'b', 'test', 'test']

You can see that at every iteration the last element will hold the value of the upcoming element, and actually you will lose the original content of the last element, i.e. 'exam' as it's getting overwritten in every iteration.

Hope it makes sense now.

like image 65
Szabolcs Avatar answered Jan 09 '23 20:01

Szabolcs