List comprehension in Python

A list comprehension is a convenient method to create lists in Python.

a = [ i for i in range( 5 ) ]
# [0, 1, 2, 3, 4]

a = [ i for i in range( 5 ) if 0 == ( i % 2 ) ]
# [0, 2, 4]

# In general any sequence of for and if
a = [ i for ... if ... for ... for ... if ... ]
a = [ i for i in range( 5 ) if 0 == ( i % 2 ) ]

# ... this is the same as ...

a = []
for i in range( 5 ):
    if 0 == ( i % 2 ):
        a.append( i )

Tried with: Python 3.2

About these ads

One thought on “List comprehension in Python

  1. [...] generator expression is very similar to list comprehension in Python. The advantage of the generator expression over list comprehension is that the resulting [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s