Why is the list overwritten by the last item when using the same name for the loop variable?

I was trying to run this script in Python and I found something really strange:

test = ['file.txt', 'file1.mkv', 'file2.mkv']                                  
for test in test:
    print(test)    
print(test)

once I run this script I was expecting an output like this:

file.txt
file1.mkv
file2.mkv
['file.txt', 'file1.mkv', 'file2.mkv']

Instead what I get is this:

file.txt
file1.mkv
file2.mkv
file2.mkv

I can't understand why the last line of output is "file2.mkv".

In the script I said to print every value in test and then print test. I never wrote to change the variable test so there is no reason why the output is not the initial variable test that I defined at the beginning.

I know I am probably wrong, but I would like to understand why.


Solution 1:

Try this:

test = ['file.txt', 'file1.mkv', 'file2.mkv']                                  
for item in test:
    print(item)    
print(test)

Your last print was printing the last item in your loop which you called test as well as your list.

Solution 2:

Python does not have the same block logic as other languages. Variables declared inside a loop are still valid after the loop.

for i in range(5):
    pass
print(i)

will output 4

whats actually happen is something like this:

# loop
i = 0
i = 1
i = 2
i = 3
i = 4
# end loop
print(i)  # print(4)

Because you named your loop variable the same as your array you are overriding the array variable with the individual values. That's the reason test contains file2.mkv after your loop.

This questions provides some further details on this topic.