Python List Comprehension

    In this tutorial, we will discuss python list comprehension, with some of its examples.

    List Comprehension

    List comprehension is a shorthand to create a list using for loop, within a line. With the help of List comprehension, we can easily create a list from existing iterable data objects (string, list, dictionary, tuple, and set).

    List Comprehension Syntax:

    [ list_element  for list_element in iterable]

    Example:

    s = "list comprehension"
    list_comprehension = [i for i in s]
    print(list_comprehension)

    Output:

    ['l', 'i', 's', 't', ' ', 'c', 'o', 'm', 'p', 'r', 'e', 'h', 'e', 'n', 's', 'i', 'o', 'n']

    Behind the code

    In the above code, we create a list, using a string s. We have written i just after the open sq. bracket [ and it represents the elements of the list.

    List Comprehension vs For loop & append

    A list comprehension is a one-line alternative technique to create a list. We can also use a logic of for loop along with list append method to create a list from an iterable.

    Example:

    Create a list from an existing iterable using for loop and append method: Create a list from an existing iterable using list comprehension
    string = "list comprehension"
    my_list = []
    for i in string:
        my_list.append(i)
    print(my_list)

    string = "list comprehension"
    my_list = [i for i in string]
    print(my_list)

    Output:
    ['l', 'i', 's', 't', ' ', 'c', 'o', 'm', 'p', 'r', 'e', 'h', 'e', 'n', 's', 'i', 'o', 'n']

    Note: Always use sq. brackets, for list comprehension.

    List comprehension vs Lambda function:

    With the help of lambda and map function, we can also create a list from an existing one within a single line.

    Example:

    string = 'techgeekbuzz'
    my_list = list(map(lambda s:s , string))
    print(my_list)

    Output:

    ['t', 'e', 'c', 'h', 'g', 'e', 'e', 'k', 'b', 'u', 'z', 'z']

    Behind the code

    In the above example, we have used the map and lambda statements to perform a similar action as a list comprehension. Though it suggested using a list comprehension technique to create a list from an existing one because it is more readable.

    Conditional List Comprehension

    We can also use the conditional statement (if) along with the for loop inside the sq. brackets to create a modified list. We often use the conditional list comprehension when we want to select specific elements from an existing list to create a new list.

    Syntax:

    list_name = [elements <for statement> <contional statement> ]

    Example:

    Write a program to create a list new_list which holds all the elements of old_list which are divisible by 3.

    old_list = [1,3,4,6,7,12,15,20,21,25,27,30]
    
    new_list = [i for i in old_list if i%3==0 ]                    # conditional list comprehension
    
    print(new_list)

    Output:

    [3, 6, 12, 15, 21, 27, 30]

    Nested if list comprehension

    Within a single list comprehension, we can have nested if statements.

    Example:

    Nested if list comprehension Equivalent Program for nested conditional list comprehension
    old_list = list(range(1,99))
    new_list = [i for i in old_list if i%3==0 if i % 5 ==0]
    print(new_list)
    old_list = list(range(1,99))
    new_list = []
    for i in old_list:
        if i%3==0:
            if i%5==0:
               new_list.append(i)
    print(new_list)

    Output:
    [15, 30, 45, 60, 75, 90]

    Behind the Code

    In the above example we have used the list comprehension to perform the nested if statements, we have also provided the equivalent program to the nested if list comprehension so you get an idea how the list comprehension works.

    If Else statement with list comprehension

    By far we have learned how can we use the if and nested if statements inside a list comprehension, now we will learn how can we use the if…else statement with list comprehension techniques. The syntax of using a using an if…else statement with list comprehension is different from all the other examples we have seen by now, in if..else list comprehension, we first use the conditional statement and then use the for loop.

    If…else list comprehension syntax:

    list_name = [elemet if...else element for....loop iterable ]
    
    

    Example:

    If..else list comprehension Equivalent program
    old_list = [1,3,4,5,6,10,12,14,15,17,19,20,24,25,29,30,35,40]
    
    new_list = [(i+1) if i%2==0 else (i-1) for i in old_list ]
    
    print(new_list)

    old_list = [1,3,4,5,6,10,12,14,15,17,19,20,24,25,29,30,35,40]
    new_list = []
    for i in old_list:
        if i%2==0:
            new_list.append(i+1)
        else:
            new_list.append(i-1)
    
    print(new_list)

    Output
    [0, 2, 5, 4, 7, 11, 13, 15, 14, 16, 18, 21, 25, 24, 28, 31, 34, 41]

    Behind the code

    In the above example, we create a new_list using old_list and write a program that adds 1 if the element is divisible by 2 else it subtracts 1 from it.

    Nested Loop in List Comprehension

    In the above example, we have only used a single loop statement, we can also use the multiple loop statements in a list comprehension.

    Example:

    Nested loop list comprehension Equivalent program
    old_list = [2,3,4,5]
    new_list = [x*y for x in old_list for y in old_list]
    print(new_list)

    old_list = [2,3,4,5]
    new_list = []
    for x in old_list:
        for y in old_list:
            new_list.append(x*y)
    
    print(new_list)

    Output
    [4, 6, 8, 10, 6, 9, 12, 15, 8, 12, 16, 20, 10, 15, 20, 25] 

    Points to remember:

    • List comprehension is a short technique to create a list from an iterable
    • It is faster than using append and for loop method
    • The element supposed to be the item of the list must be written just after the open sq. bracket.