Python – List Comprehension

List comprehension in Python is creation of lists from iterables and other lists, following a condition. It is lightning fast and it looks nice, because it is a 1 liner. In this article, I will show a few examples of it. The GitHub repo with the code is located here.

List not in list

Or with other words, make a list of the chars, which are not in a given list:

    #list not in list
    vowels = ['a', 'u', 'e', 'i', 'o', 'A', 'U', 'E', 'I', 'O']
    text = "https://vitoshacademy.com is my blog."
    no_vowels = ''.join([x for x in text if x not in vowels])
    print(no_vowels)
https://vtshcdmy.cm s my blg.

Put every second unit in a list

Iterate through a list and make a new list with every second unit of it. Two methods are given:

    #print every second letter
    every_second = text[::2]
    print(every_second)
    every_second = "".join([x for i, x in enumerate(text) if i % 2 == 1])
    print(every_second)
hts/vtsaaeycmi ybo.
tp:/iohcdm.o sm lg

List in list

Checking if each element from a list of elements is present in another list of elements is quite a trivial task, that occurs often:

    #list in list
    only_vowels = "".join([x for x in text if x in vowels])
    print(only_vowels)
ioaaeoio

Build a dictionary with list comprehension (Dictionary comprehension)

Building a dictionary with 1 line is quite fascinating, once you know what to do. The 2 dictionaries below get the char position in the Ascii table and count the occurencies of the char.

    #dictionary from a string
    letters = list(text)
    occurrences = {char: letters.count(char) for char in letters}
    print(occurrences)
    char_dict = {char: ord(char) for char in letters}
    print(char_dict)
{'h': 2, 't': 3, 'p': 1, 's': 3, ':': 1, '/': 2, 'v': 1, 'i': 2, 'o': 3, 'a': 2, 'c': 2, 'd': 1, 'e': 1, 'm': 3, 'y': 2, '.': 2, ' ': 3, 'b': 1, 'l': 1, 'g': 1}
{'h': 104, 't': 116, 'p': 112, 's': 115, ':': 58, '/': 47, 'v': 118, 'i': 105, 'o': 111, 'a': 97, 'c': 99, 'd': 100, 'e': 101, 'm': 109, 'y': 121, '.': 
46, ' ': 32, 'b': 98, 'l': 108, 'g': 103}

Matrix creation with list comprehension

This one is self-explanatory, but still, 3D matrix with 1 line is something worth seeing (hopefully not in a production code):

    #creation of 1D matrix:
    matrix1D = [j for j in range(100,105)]
    print(matrix1D)

    #creation of a 2D matrix:
    matrix2D = [[j for j in range(4)] for i in range(10)]
    print(matrix2D)

    #creation of a 3D matrix:    
    matrix3D = [[[j for j in range(10,12)] for i in range(2)] for z in range(2)]
    print(matrix3D)
[100, 101, 102, 103, 104]
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
[[[10, 11], [10, 11]], [[10, 11], [10, 11]]]

2D matrix to a list

Not a lot of reasons to do this, but still, once you can do it…

    #2D matrix to list:
    flattened = [num for sublist in matrix2D for num in sublist]
    print(flattened)
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

List of numbers, divisable by a set of other numbers

Sounds like fun, unless you are asked to do it with list comprehensions. Anyway, it is not on 1 line.

    #numbers, divisable by a set of other numbers
    numbers = [num for num in range(100, 150)]
    set_of_other_numbers = [num for num in range(2, 20)]
    divisable = [num for num in numbers if any([num % x == 0 for x in set_of_other_numbers])]
    print("divisable: {0}\n".format(divisable))
divisable: [100, 102, 104, 105, 106, 108, 110, 111, 112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 132, 133, 134, 
135, 136, 138, 140, 141, 142, 143, 144, 145, 146, 147, 148]

List of numbers, non-divisable by a set of other numbers

This is a bit more interesting, I guess. Anyway, completely the opposite of the previous.

    #numbers, non divisable by a set of other numbers
    non_divisable =  [num for num in numbers if all([num % x != 0 for x in set_of_other_numbers])]
    print(non_divisable)
    
    #numbers, non divisable by a set of other numbers, simple
    non_divisable = [num for num in numbers if num not in divisable]
    print(non_divisable)
[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]
[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]

GitHub repo with code.