-5

I encountered a issue on using list in python.

with open('test.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    line = [l.rstrip('\n') for l in lines[:2]]
    
    print(line[0])
    ll = []
    for lin in lines[2:]:
        ll.append(lin)
        break
    print(line[0])

the result is:

0;;no2;;the third part3;;the fourth part4
0;;no2;;the third part3;;the fourth part4

But when I turn the variable lin to line.(the same name mentioned)

with open('test.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    line = [l.rstrip('\n') for l in lines[:2]]
    
    print(line[0])
    ll = []
    for line in lines[2:]:
        ll.append(line)
        break
    print(line[0])

the result is:

0;;no2;;the third part3;;the fourth part4
0

It apparently shows that the value of line has been change during the for loop when sharing the same variable name.

lucky
  • 1
  • 3
  • The line variable is not *changed* in this case, rather it has been *re-assigned*. It is now pointing to the loop variable `line` - the value from the last loop iteration – rv.kvetch Sep 26 '21 at 05:08
  • 1
    @rv.kvetch the reference of `line` has been change because of the same variable name? I previously think the variable in loop is just temp, and therefore doesn't affect other variable. So all types not just `list` in python will come across the same issue? – lucky Sep 26 '21 at 05:16
  • Yes, that is correct. this will apply regardless of what type `line` is, for example. Only it’s reference has changed, and the original reference to the earlier `line` has been lost, due to the for loop. – rv.kvetch Sep 26 '21 at 11:30

1 Answers1

2

This has nothing to do with how lists are stored. The scope of for loop variables do not work how you expect.

It apparently shows that the value of line has been change during the for loop when sharing the same variable name.

This is expected behavior. Unlike other languages, python does not create a new scope for for loops.

Here's more details on the subject: Scoping in Python 'for' loops

Andrew-Harelson
  • 1,022
  • 3
  • 11