Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension overriding value

have a look at the following piece of code, which shows a list comprehension..

>>> i = 6
>>> s = [i * i for i in range(100)]
>>> print(i)

When you execute the code example in Python 2.6 it prints 99, but when you execute it in Python 3.x it prints 6.

What were the reason for changing the behaviour and why is the output 6 in Python 3.x?

Thank you in advance!

like image 365
Joschua Avatar asked Jan 01 '11 20:01

Joschua


People also ask

Is list comprehension pythonic?

List comprehensions are often described as being more Pythonic than loops or map() .

What are the advantages of using list comprehensions?

Some of the benefits are as follows: List Comprehensions are easy to understand and make code elegant. We can write the program with simple expressions. List comprehensions are way faster than for loop and other methods like a map.

How does list comprehension work in Python?

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.

Can we use while loop in list comprehension?

No, you cannot use while in a list comprehension.


2 Answers

The old behaviour was a mistake but couldn't easily be fixed as some code relied on it.

The variable i inside the list comprehension should be a different i from the one at the top level. Logically it should have its own scope which does not extend outside the comprehension as its value only makes sense inside the comprehension. But in Python 2.x due to an implementation detail the scope was larger than necessary causing the variable to "leak" into the outer scope, causing the confusing results you see.

Python 3.0 was deliberately not intended to be backwards compatible with previous releases, so they used the opportunity to fix this undesirable behaviour.

In Python 2.3 and later releases, a list comprehension “leaks” the control variables of each for it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work in Python 3.0

Source

like image 157
Mark Byers Avatar answered Oct 23 '22 19:10

Mark Byers


Yes, there is a reason, and the reason is that they didn't want the temporary variable in a list comprehension to leak into the outer namespace. So it is an intentional change that is a result of list comprehensions now being syntactic sugar for passing a generator expression to list().

Ref: PEP3100.

like image 45
Lennart Regebro Avatar answered Oct 23 '22 18:10

Lennart Regebro