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:

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:

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:

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.

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):

2D matrix to a list

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

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.

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.

GitHub repo with code.

Tagged with: , , , , ,