Very interesting loop behavior: lists the changes. What's happening?

Somehow after that

list2 = [x for x in range(10)] list1 = [ x for x in range(10,20)] for k, list1 in enumerate([list1,list2]): for number, entry in enumerate(list1): print number, entry 

suddenly id(list2)==id(list1) evaluates to True? What's happening? while the loop is running, this doesn't seem to be the way the first output is expected:

0 10, 1 11, 2 12, ... 0 0, 1 2, 2 3, ...

the second, although it gives:

0 0, 1 1, 2 2 ...

How is this possible?

Just change the code to:

 list2 = [x for x in range(10)] list1 = [ x for x in range(10,20)] 

Gets an exemption from this behavior.

  for k, NEWVAR in enumerate([list1,list2]): for number, entry in enumerate(list1): print number, entry 
+5
source share
3 answers

You write:

 list1 = [ x for x in range(10,20)] 

And then:

 for k, list1 in ... 

You use the same name list1 for two different but mixed objects! Nothing good will come of it.

Just use a different name for the loop:

 for k, l in enumerate([list1,list2]): for number, entry in enumerate(l): 

Remember that in Python there are only two areas, roughly speaking:

  • and
  • scope.
+6
source

You redirect list1 to a for loop:

 for k, list1 in enumerate([list1,list2]): 

which means that at the last iteration you are implicitly doing list1 = list2

From docs

enumerate () returns a tuple containing a counter (from the beginning, which defaults to 0), and values ​​obtained from iterating over the sequence

+2
source

In the for loop, the last value assigned to list1 ist list2 , and therefore the equality

You expect the variables in the for loop to be limited to the loop, but that is not the case. How in:

 for i in range(0, 2): pass print(i) 

What outputs:

 1 
0
source

Source: https://habr.com/ru/post/1241985/


All Articles