Python 2.0 list comprehensions - Sample examples

Comprehensions are constructs that allow sequences to be built from other sequences. List comprehensions was introduced in Python 2.0. The concise and clean code of list comprehension inspired to introduce dictionary and set comprehensions.

Components of List comprehensions :- 

1. An Input Sequence  - From which new sequence is built
2. A variable representing members of the input sequence.
3. An conditional expression [ Optional ]
4. An output expression producing elements of the output list - all elements of input sequence which satisfies conditional expression, if available. 
List comprehension structure


1. Use a list comprehension print even numbers from 0 to n(n is some arbitrary value). 
>>> values = [x for x in range(0, n+1) if x%2==0]
>>> values
[0, 2, 4]
Here range(0, n+1) is input sequence, x is variable representing members of the input sequence, if x%2==represents conditional expression and x at beginning generates output sequence.

2. Using list comprehension print the Fibonacci Sequence in comma separated form for given input n.
def f(n):    
    if n == 0: 
            return 0    
    elif n == 1: 
            return 1    
            return f(n-1)+f(n-2)
values = [str(f(x)) for x in range(0, n+1)] 
print ",".join(values)
O/P:- 4
Here str(f(x)) (converting int to string) generates output sequence as list.

3.Using list comprehension, write a program to print the list after removing the 0th, 2nd, 4th , 6th elements in [2,14,45,19,18,10,55].
li = [12,24,35,70,88,120,155] 
li = [x for (i,x) in enumerate(li) if i%2!=0] 
print li
O/P:-  [24, 70, 120]

4. Using list comprehension, write a program to print the list with numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]
>>> li =[12,24,35,70,88,120,155]
>>> li = [x for x in li if x%5 ==0 and x%7 ==0]
>>> li
[35, 70]

Note:- Python 3.0 supports Set and Dict comprehensions too.


Previous Post Next Post