Python list comprehension

Standard

I think  list comprehension is one of  the advanced feature that make python more userfriendly and efficient . Do you know what is list comprehension ? how can be use it ? .This post will help you to learn some basic ideas about list comprehension in  python.

What is a list comprehension?

Mainly list comprehension  feature is indroduced in python version 2.0 . It  is an elegent way  to define and  create lists in python. Using list comprehension we can create  new list from an existing list  and each element in the new list  is the result of some operations applied to each element in the old list. List comprehension is not a complicated idea it fit a for loop,if statement and assignment all are in one line . Let me explain concept behind list comprehension using some examples.

Here is a simple program which create a list of  squares of even numbers in the range of 10

>>>L=[]

>>>for x in range(10):

   if x%2 ==0:

     L.append(x**2)
>>>L
[0,4,16,36,64]

Now i am going to write same program using list comprehension technique


>>L=[x**2  for x in range(10) if x %2==0]
>>L
[0,4,16,36,64]

above two codes are identical, you can see that list comprehension is more good and  you get to see more of the code in one view. Another important factor is that list comprehension is the complete substitute for lambda() functions as well as the functions map(),filter() ,reduce().

Basic syntax  is:

[expr for  item1 in  seq1 for item2 in seq2 … for itemx in seqx if condition]

  • the list comprehension starts with a ‘[‘ and ‘]’, to help you remember that the result is going to be a list
  • there’s an expression based on the variable used for each element in the old list
  • the word ‘for’ followed by the variable name to use followed by the word ‘in'
  • the old list

Here are some more examples using list comprehension

Cross product of two sets


>>>colours=["red","blue","yellow"]

>>things=["house'","car","tree"]

>>>coloured_things=[(x,y) x in colours for y in things]

print coloured_things

[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree')]

Following list comprehension create a pythagorean triples

>>>[(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29)]

Calculation of prime numbers between 1 and 100

>>>noprimes = [j for i in range(2, 8) for j in range(i*2, 100, i)]
>>>primes = [x for x in range(2, 100) if x not in noprimes]
>>>print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>>

List comprehension and generator comprehension

If you don’t know about generators in python please go to this link https://neethutv.wordpress.com/2012/01/11/generators-an-advanced-concept-in-python/ and come back to this article. Generator  comprehensions are introduced with python 2.6. They are simply generator expressions with paranthesis .The syntax and way of working of generator comprehension is same way as list comprehension , but most important difference is that generator comprehension return a generator object instead of list. Generator comprehensions  always have to written in paranthesis.  Here some examples of generator comprehensions


>>>x = (x **2 for x in range())
>>>x
<generator object <genexpr> at 0xb76acb44>

>>>for i in x:

  print i

0,1,4,9,16

List comprehension is one of the simple and useful feature of python.  It is  faster than equivalent for loop, but map(),filter() ,reduce() are generally faster than list comprehension. One thing to note that list comprehension create a new list. The new list is rebound the same name.

l = [ foo(i) for i in l ]

but a new list is created ,any other name that refer to original list will not changed. This is a rarely problem so to avoid this type of problems just use slice assignment instead of normal assignment.

l[:] = [foo(i) for i in l]

I think list comprehension is quite easy to use and can make code that manipulates lists shorter and more readble.

Leave a comment