Friday 28 March 2014

Python - List Comprehensions

"List Comprehensions" in python is a concept used to construct lists in a easy way, like a mathematician does on a piece of paper. These listcomp (I'll be using listcomp  instead of List Comprehensions in the remaining of my description) are useful when there is a requirement of doing certain kind of operations on all the list elements. Say that you are having list 'a' as shown below:

  >>>a = [1,2,3,4,5,6]
  >>>
You want to create another list b which contains squares of elements in list a. We can do that using the below python script:
  a = [1,2,3,4,5,6]
  for x in a:
     b.append(x*x)  
  print(b)



Using listcomp we can do that easily.
  a = [1,2,3,4,5,6]
  b = [ x*x for x in a]
  print(b)
Listcomp conssts of an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression  in the context of the for and if clauses which follow it.

Let us take another example. Say we have 2 lists 'a' and 'b' and wish to build another list 'c' containing tuples of 'a' and 'b' i.e., 

  >>>a = [1,2,3]
  >>>b = [10,20,30]
  >>>c = [(1,10),(1,20),(1,30),(2,20),(2,30),(2,30),(3,10),(3,20),(3,30)]
This can be done using listcomps as below:
  a = [1,2,3]
  b = [10,20,30]
  c = [(x,y) for x in a for y in b if x!= y ]
  print(c)
Let us look into some complex listcomps. Observe the below piece of code
  nonprimes = [j for i in range(2, 8) for j in range(i*2,50,i)]
  #above listcomp creates a list with all nonprime numbers between 2 and 50

  primes = [x for x in range(2, 50) if x not in noprimes]
  #above listcomp creates a list all prime numbers between 2 and 50 by checking
  # into nonprimes list

  print(primes)
The comments in the above code snippet explains the liscomp generated. We can even make the above code simple by using nested listcomps:
  primes = [x for x in range(2, 50) if x not in [j for i in range(2, 8) for j in range(i*2, 50, i)]]

  print(primes)
As shown above we can build very complex lists using listcomps. In coming post I'll discuss how to convert the listcomp to iterator loops. Happy coding....:)

Note: I've used 3.3 python interpreter to run the code 

0 comments:

Post a Comment