List Comprehension - Breaking down the syntax

Hello!

I understand that list comprehensions are an elegant way to define and create lists based on existing lists but I’m unsure as to how they work. Taking the following example from Abruptly Goblins can someone please break it down and explain it to me:

unable_to_attend_best_night = [gamer for gamer in gamers if game_night not in gamer['availability']]

There’s a couple of things you can do here to make it easier for yourself, one is to re-format the comprehension itself-

unable_to_attend_best_night = [
    gamer  # expression
    for gamer in gamers  # target name and for clause
    if game_night not in gamer['availability']  # optional if clause
]

This style may be a little more readable and so may be useful for more complex comprehensions or in whenever you feel the single line is becoming too busy. You can just about read it like a sentence in English now.

The second route to understanding them might be to convert this to a regular for loop. Breaking it up like the example above makes this much easier. For the given example, this would be the equivalent for loop-

unable_to_attend_game_night = []
for gamer in gamers:
    if game_night not in gamer['availability']:
        unable_to_attend_game_night.append(gamer)

You can see here the order doesn’t even change much and the greatest difference is the location of the append (compared to expression at start of comprehension). If you can remember that the expression at the start of the list comprehension is what you’re after then you’ll probably find them much easier to work with since the order is then basically the same as a regular loop.

Section of the docs that may be useful-
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
More information and a little general advice on when/ when not to use them-

2 Likes