Python list and set comprehensions

When we need to convert certain elements from an iterable object, generator, etc. to a list or set, it is possible to do it in just one line thanks to the list an set comprehensions. Lets consider the following list of dictionaries.

>>> days = [{'day': 'monday', 'index': 1}, {'day': 'tuesday', 'index': 2}]

The way to do it without this tool is to store the key index of the dictionaries would be:

>>> l = list()
>>> for day in days:
...    l.append(day['index'])
>>> l
[1, 2]

If we use list comprehensions we would do it like this:

>>> l = [day['index'] for day in days]
>>> l
[1, 2]

Similarly, we could use set comprehensions when needed:

>>> s = {day['index'] for day in days}
>>> s
set([1, 2])

In this examples it doesn’t look like a big deal, but when we work with complex objects and we want to have a neat and legible code (and with less indentation), it is a great alternative!

You can find more examples in the link below from

Sources: | Data Structures (List Comprehensions) | Data Structures (Sets)