2

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 4
    In the loop test is the local variable `test` (each element of the list `test`). After the loop, `test` is the top variable `test` (the list) – Corralien Jan 23 '22 at 20:50
  • 1
    Try using `for t in test` to see if you can understand what is happening. – Sash Sinha Jan 23 '22 at 20:50
  • Maybe you can try to run here to see what is going on - pythontutor.com – Daniel Hao Jan 23 '22 at 20:51
  • Does this answer your question? [For loop overriding outer variables instead of creating new ones](https://stackoverflow.com/questions/53356539/for-loop-overriding-outer-variables-instead-of-creating-new-ones) – mkrieger1 Jan 23 '22 at 21:04

2 Answers2

3

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
pugi
  • 323
  • 1
  • 12
3

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.

Markus
  • 91
  • 5