Python Programming Language List Comprehensions

What is list comprehensions?

  • List comprehension provides the option to create lists. Creating new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
  • List comprehension provides the new list result based on evaluating the expression in the context of the for loop and if clauses.
  • List comprehension consists of brackets (starting '[' and ending ']')containing an expression followed by a for clause, then zero or more for or if clauses.

List comprehensions syntax:

[ expression for item in list if conditional ]
  • List Comprehensions Example
  • lists = [val*2 for val in range(6)]
    print lists;
    
    Output:
    [0, 2, 4, 6, 8, 10]
    
    Suppose we need create above list without list comprehensions,
    lists = []
    for val in range(10):
        lists.append(val*2)
    
    print lists;
    

    List comprehensions with filter if clauses

    Filters elements in the iteration and transforming the values based on expression.
    lists = [val*3 for val in range(10) if val%2 == 0]                              
    print lists; 
    
    Output:
    [0, 6, 12, 18, 24]
    

    List comprehensions general format

    *new_list*  = [*transform*    *iteration*     *filter*]
    

    List comprehensions with calling method

    numbers = ['  one', '  two ', 'three  ']                                        
    new_list = [number.strip() for number in numbers]                               
    print new_list; 
    
    Output:
    $ python list-coprehension.py
    ['one', 'two', 'three']
    

    List comprehensions for each element starts with capital first letter in list

    numbers = ['one', 'two', 'three']                                               
    new_list = [(number[0].upper() + number[1:]) for number in numbers]             
    print new_list;   
    
    Output:
    $ python list-coprehension.py
    ['One', 'Two', 'Three']
    

    List comprehensions to extract numbers in string

    string = "test 2345 numbers 322 43!";                                           
    new_list = [num for num in string if num.isdigit()]                             
    print new_list;  
    
    Output:
    $ python list-coprehension.py
    ['2', '3', '4', '5', '3', '2', '2', '4', '3']
    

    List comprehensions to extract letters in string

    string = "test 2345 numbers 322 43!";                                           
    new_list = [ch for ch in string if ch.isalpha()]                                
    print new_list;                                                                 
    
    Output:
    $ python list-coprehension.py
    ['t', 'e', 's', 't', 'n', 'u', 'm', 'b', 'e', 'r', 's']
    

    List comprehensions to extract lower letters in string

    string = "Test 2345 Numbers 322 43!";                                           
    new_list = [ch for ch in string if ch.islower()]                                
    print new_list; 
    
    Output:
    $ python list-coprehension.py
    ['e', 's', 't', 'u', 'm', 'b', 'e', 'r', 's']
    

    List comprehensions with tuple values

    new_list = [num, num**3 for num in range(1, 10)]                                
    print new_list; 
    
    Interpreter error is generated because tuple values should be placed using parantheses'(' and ')'.
    $ python list-coprehension.py
      File "list-coprehension.py", line 1
        new_list = [num, num**3 for num in range(1, 10)]
                                  ^
    SyntaxError: invalid syntax
    
    Correct way
    new_list = [(num, num**3) for num in range(1, 10)]                              
    print new_list;
    
    Output:
    $ python list-coprehension.py
    [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125), (6, 216), (7, 343), (8, 512), (9, 729)]
    

    List comprehensions with array values

    new_list = [[num, num**2, num**3] for num in range(1, 10)]                      
    print new_list;
    
    Output:
    $ python list-coprehension.py
    [[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343], [8, 64, 512], [9, 81, 729]]
    

    List comprehensions with math function

    from math import pi                                                             
    new_list = [str(round(pi, i)) for i in range(5)]                                
    print new_list;  
    
    Output:
    $ python list-coprehension.py
    ['3.0', '3.1', '3.14', '3.142', '3.1416']
    

    Nested List Comprehensions

    The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

    Finding Average Mark with different rounding decimals

    marks = [[67,87,54], [98, 56, 78, 86], [56, 89]];                               
    new_list = [[round(float(sum(mark))/len(mark), i) for i in range(1,4)] for mark in marks]
    print new_list;  
    
    Output:
    $ python list-coprehension.py
    [[69.3, 69.33, 69.333], [79.5, 79.5, 79.5], [72.5, 72.5, 72.5]]
    

    Finds prime numbers

    no_primes = [no_prime for div in range(2, 8) for no_prime in range(div*2, 100, div)]
    primes = [num for num in range(2, 100) if num not in no_primes]                 
    print primes;  
    
    Output:
    $ python list-coprehension.py
    [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]
    

    Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

    Email Facebook Google LinkedIn Twitter
    ^