List Comprehension (Python)
A list comprehension is a concise way to build a list.
It is often used in place of a for loop when creating a new list based on an existing list. For example, let’s say we have a list of pitches (MIDI note numbers) and we would like to generate a list of pitch classes:
my_pitches = [60, 71, 56, 62, 65, 72, 60, 48]
Our first thought might be to convert each pitch to a pitch class using a for loop and append them to a new list:
pitch_classes =  for x in my_pitches: x = x % 12 pitch_classes.append(x)
(For help with the modulo % function check out this module.)
A list comprehension allows us to do the same thing with a single line of code:
pitch_classes = [x % 12 for x in my_pitches]
The full comprehension syntax is [expression for value in iterable if condition]. This means that for every value in the iterable (like a list or other sequence), we generate a new list by applying the expression. The optional if statement at the end specifies any conditions.
We could expand the statement above by using the if statement to exclude any negative numbers:
more_pitches = [60, -71, 56, -62, 65, 72, 60, 48] pitch_classes = [x % 12 for x in more_pitches if x >= 0]