Comprehensions


By HyperNeutrino
Written 12 days ago

If you want to construct a list by for looping through another list (for example, going through a list and adding one to each element), you can do the following:

a = [1, 2, 3, 4]
b = []
for e in a:
    b.append(e + 1)
print(b)

This is perfectly valid. However, this is much longer than necessary, and also requires creating a new variable and writing out a for block. There is another construction that allows us to create lists in this fashion on one line:

a = [1, 2, 3, 4]
b = [e + 1 for e in a]

The basic structure is this:

[new_element for old_element in collection]

This acts similarly to a for old_element in collection loop, and the elements in the final list are constructed by new_element.

Another component that can be added is an if clause at the end:

[new_element for old_element in collection if condition]

This translates to the following:

b = []
for old_element in collection:
    if condition:
        b.append(new_element)

Note that condition and new_element are expressions and both can contain evaluations based on old_element.

This works with lists, sets, and dicts, like so:

[f(e) for e in a if c]
{f(e) for e in a if c}
{key: value for e in a if c}

An example of the usage for dictionaries:

a = [1, 2, 3, 4]
d = {e + 1: e + 2 for e in a}

You cannot make tuples this way. Without going into too much detail, since putting it into brackets is just a way to bypass order of operations, an "un-bracketed" comprehension expression becomes a generator - basically, a list that generates its values as you loop for more memory efficiency.

You can loop through generators and turn them into lists, tuples, or sets:

list(a for b in c)
set(a for b in c)
tuple(a for b in c)

That is how you make a tuple with a comprehension syntax.