
Python 201: List Comprehensions - driscollis
http://www.blog.pythonlibrary.org/2012/07/28/python-201-list-comprehensions/
======
dlitz
The preferred syntax, which is more flexible and doesn't leak the loop
variable, is to use generator expressions:

    
    
      >>> x = ['1', '2', '3', '4', '5']
      >>> y = list(int(i) for i in x)
      >>> y
      [1, 2, 3, 4, 5]
    

It also works for tuples:

    
    
      >>> y = tuple(int(i) for i in x)
      >>> y
      (1, 2, 3, 4, 5)
    

And for dicts:

    
    
      >>> y = dict((i, int(i)) for i in x)
      >>> y
      {'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}
    

And if you want a lazily-evaluated generator:

    
    
      >>> y = (int(i) for i in x)
      >>> y
      <generator object <genexpr> at 0xb7655eb4>
    

Also, as I mentioned before, generator expressions don't leak the loop
variable:

    
    
      >>> i = 42
      >>> y = list(int(i) for i in x)
      >>> i
      42
      >>> y = [int(i) for i in x]
      >>> i
      '5'
    

See <http://www.python.org/dev/peps/pep-0289/>

------
pfranz
List comprehensions are extremely handy. I'm sure it's probably hard to come
up with simple examples without using something that can be done better
another way, but the last few example could be done with map() and
itertools.chain(). I'm surprised itertools isn't mentioned in the Python
documentation he linked to.

~~~
alwaysdoit
List comprehensions are actually preferred over map() because they are
typically clearer. Guido at one point was actually planning to remove them
from Python 3000.

<http://www.artima.com/weblogs/viewpost.jsp?thread=98196>

I do wish itertools.chain() was a built-in, however. So useful.

