Python list comprehension overriding value

后端 未结 4 1534
小蘑菇
小蘑菇 2020-11-30 13:58

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

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


        
4条回答
  •  难免孤独
    2020-11-30 14:30

    Mark Byers answered it perfectly.

    just as a side note..
    in Python 2.x, if you change your brackets to parens (creating a generator expression instead of a list comprehension), you will notice that the control variable is not leaked.

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

    vs.

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

    (of course, in Python 3, this is fixed and list comprehensions no longer leak control variables)

提交回复
热议问题