5

Somehow after doing this

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) evaluated to True? What on earth is happening? while the loop is running this does not seem to bee the case the first output is as expected :

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

the second though gives:

0 0, 1 1, 2 2...

How is this possible?

Simply changing the code to:

list2 = [x for x in range(10)]

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

Gets rid of this behaviour.

 for k, NEWVAR in enumerate([list1,list2]):
    for number, entry in enumerate(list1):
        print number, entry 
Kuhlambo
  • 371
  • 3
  • 13

3 Answers3

6

You write:

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

And then:

for k, list1 in ...

You are using the same name list1 for two different, but intermixed objects! Nothing good will come out of this.

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 scopes, roughly speaking:

  • module scope and
  • function scope.
rodrigo
  • 94,151
  • 12
  • 143
  • 190
2

You are re-assigning list1 in your for loop:

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

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

From the docs

enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

Railslide
  • 5,344
  • 2
  • 27
  • 34
  • but should the loop not create a new variable in the namescope of the loop? – Kuhlambo Feb 01 '16 at 11:15
  • @pindakaas: no, the variable is not limited to the for loop scope. see http://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – Railslide Feb 01 '16 at 11:19
0

In the for loop the last value assigned to list1 ist list2 and that's why the equality holds true

You are expecting the variables in the for loop to be restricted to the loop but it's not the case. As in:

for i in range(0, 2):
    pass

print(i)

Which outputs:

1
mementum
  • 3,153
  • 13
  • 20