1

I've noticed that when you a run a list comprehension over a pre-existing list, the list is unchanged after the process.

Except, however, if the local names in the comprehension are the same is your initial variable.

Why is this?

Example:

>>> y=[1,2,3,4,5]

>>> [X**2 for X in y]
[1, 4, 9, 16, 25]
>>> y
[1, 2, 3, 4, 5]

>>> [y**2 for y in y]
[1, 4, 9, 16, 25]
>>> y
5

As you can see, in the second example, y has been changed to the integer 5.

Charon
  • 2,344
  • 6
  • 25
  • 44
  • 3
    A list comprehension doesn't introduce a new variable scope. If you reuse the same variable name, it's going to overwrite that variable with the last value in the list. – Mark Reed Jan 14 '14 at 20:51

1 Answers1

2

You are in effect rebinding y to contain the last value of the original y.

It's no different to, say, the following:

In [18]: [x for x in range(5)]
Out[18]: [0, 1, 2, 3, 4]

In [19]: x
Out[19]: 4

except that your code uses y for two different things, confounding the issue.

NPE
  • 486,780
  • 108
  • 951
  • 1,012