Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Unpacking
  • List Comprehensions
  • Pairing and Numbering
  • Filtering
  • Nested Comprehensions
  • Dictionaries

Syntactic Sugar

Python has shorter ways to write many familiar loops. These forms are called syntactic sugar. We’ll use them to build and filter collections, and compare each version with the loop it replaces so we can decide which is easier to read.

Unpacking

Unpacking assigns successive values to separate names. It gives us a way to name the fields of a record instead of repeatedly looking them up by position. An iterable supplies values one at a time, as lists, tuples, and strings do in a for loop. In first, second = values, the first name receives the first value and the second name receives the second value.

We’ll organize a music library, first displaying a numbered catalog and then selecting a playlist from several albums. We’ll use Billy Joel’s “Vienna,” Stephen Sanchez’s “Evangeline,” Noah Kahan’s “Stick Season,” and later Benson Boone’s “Beautiful Things.” The durations and play counts are made up to keep the arithmetic simple.

Create music_library.py with these records:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]
play_counts = [2, 0, 5]

Each song is a (title, minutes) tuple. The play counts correspond to the songs in the same order. Each example below includes its input data. Copy a block into music_library.py and run it with python music_library.py. The completed program prints the catalog and playlist reports.

We could retrieve a song’s fields with song[0] and song[1]. Unpacking assigns both fields at once:

song = ('Vienna', 5)
title, minutes = song
print(title)    # Vienna
print(minutes)  # 5

We can also unpack each record as a loop visits it:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]

total = 0
for title, minutes in songs:
    total += minutes
print(total)  # 12

total += minutes means total = total + minutes.

With ordinary unpacking, we need one value for each name. If an iterable supplies too few or too many, the assignment raises ValueError. Trying to unpack a value that is not iterable raises TypeError.

These assignments demonstrate the two kinds of failure. Try them separately:

title, minutes = ('Vienna', 5, 'live')  # ValueError: three values for two names
title, minutes = 5  # TypeError: an integer is not iterable

Strings supply their characters, so this assignment succeeds:

first, second = 'EP'
print(first, second)  # E P

Python evaluates the right side before assigning the names on the left. That lets an assignment use the old values of both names when swapping them.

current, next_song = 'Vienna', 'Evangeline'
current, next_song = next_song, current
print(current, next_song)  # Evangeline Vienna

What happens if one record in songs contains three fields instead of two? Predict where the total-duration loop will stop, then try adding an extra field to the second song in a separate copy of the file.

List Comprehensions

A list comprehension is a way to build a new list in one expression. In [expression for item in collection], Python takes each item in order, evaluates the expression, and adds the result to the new list. This does the same work as a loop with an append inside it.

To display a song’s fields together, build a label such as 'Vienna (5 min)'. The f before a string lets us insert the values inside braces:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]

labels = []
for title, minutes in songs:
    labels.append(f'{title} ({minutes} min)')
print(labels)  # ['Vienna (5 min)', 'Evangeline (3 min)', 'Stick Season (4 min)']

A comprehension expresses the same calculation:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]

labels = [f'{title} ({minutes} min)' for title, minutes in songs]

Start with for title, minutes in songs when tracing it. For each song, Python evaluates the expression on the left and adds that label to the new list.

The result expression can produce any type of value, including a number, string, tuple, or list. A comprehension can select part of an input record or transform its contents. Building the result does not itself change the input collection.

Keep just the title field:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]

titles = [title for title, minutes in songs]
print(titles)  # ['Vienna', 'Evangeline', 'Stick Season']

Create uppercase copies of those strings:

titles = ['Vienna', 'Evangeline', 'Stick Season']

print([title.upper() for title in titles])  # ['VIENNA', 'EVANGELINE', 'STICK SEASON']
print(titles)  # ['Vienna', 'Evangeline', 'Stick Season']

Suppose the music player expects durations in seconds. Write a comprehension that produces [('Vienna', 300), ('Evangeline', 180), ('Stick Season', 240)] from songs. Put parentheses around the (title, seconds) pair so it becomes one item in the result.

The expression runs once per item. Iterating over a string gives us one character at a time. Iterating over a list of strings gives us one whole string at a time. An empty input produces [] without evaluating the expression.

print([letter.upper() for letter in 'EP'])   # ['E', 'P']
print([title.upper() for title in ['EP']])   # ['EP']
print([title.upper() for title in []])       # []

Pairing and Numbering

Sometimes related values are stored in separate collections. zip combines iterables by position: their first items go together, then their second items, and so on. It produces a tuple for each position as we iterate over it. By default, it stops as soon as any input runs out of items.

Each catalog row needs a play count, stored in a separate list in the same order as the songs:

titles = ['Vienna', 'Evangeline', 'Stick Season']
play_counts = [2, 0, 5]

print(list(zip(titles, play_counts)))  # [('Vienna', 2), ('Evangeline', 0), ('Stick Season', 5)]

list(...) collects the pairs so we can print them together. We can also loop over zip directly to combine the formatted labels and play counts:

play_counts = [2, 0, 5]
labels = ['Vienna (5 min)', 'Evangeline (3 min)', 'Stick Season (4 min)']

rows = []
for label, count in zip(labels, play_counts):
    rows.append(f'{label}: {count} plays')

The corresponding comprehension is:

play_counts = [2, 0, 5]
labels = ['Vienna (5 min)', 'Evangeline (3 min)', 'Stick Season (4 min)']

rows = [f'{label}: {count} plays' for label, count in zip(labels, play_counts)]

If the third play count is missing, there is no pair for 'Stick Season':

titles = ['Vienna', 'Evangeline', 'Stick Season']

print(list(zip(titles, [2, 0])))  # [('Vienna', 2), ('Evangeline', 0)]

In a separate copy, change play_counts to [2, 0] and rebuild rows. If we want to display every song, what should we check about the lengths of the two input lists?

enumerate produces (number, item) pairs as it visits an iterable. It is useful when we need both an item’s value and its position. The number increases by one for each item, starting at zero unless we supply start. Changing start changes the numbering without skipping or rearranging the input.

With the default start, the numbers are the list indices:

titles = ['Vienna', 'Evangeline', 'Stick Season']

print(list(enumerate(titles)))  # [(0, 'Vienna'), (1, 'Evangeline'), (2, 'Stick Season')]

A comprehension can use those pairs too:

titles = ['Vienna', 'Evangeline', 'Stick Season']

print([f'{i + 1}. {title}' for i, title in enumerate(titles)])
# ['1. Vienna', '2. Evangeline', '3. Stick Season']

For the catalog, start at 1 and print the completed rows:

rows = ['Vienna (5 min): 2 plays', 'Evangeline (3 min): 0 plays', 'Stick Season (4 min): 5 plays']
total = 12

for number, row in enumerate(rows, start=1):
    print(number, row)
# 1 Vienna (5 min): 2 plays
# 2 Evangeline (3 min): 0 plays
# 3 Stick Season (4 min): 5 plays
print('Total:', total, 'min')  # Total: 12 min

Filtering

Filtering selects items that satisfy a condition. In [expression for item in collection if condition], Python checks the condition before evaluating the result expression for that item. The condition determines which items contribute, and the expression determines what gets stored. Filtering can reduce the number of results, while transforming an item changes the value stored for it.

The catalog displays every song. Now we’ll build a playlist of songs at most four minutes long and count how many each album contributes. The first album contains our original songs. We also include a live album and an empty album:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]

album_names = ['Favorites', 'Live', 'Unsorted']
albums = [
    songs,
    [('Evangeline', 6), ('Beautiful Things', 2)],
    [],
]
limit = 4

First select songs from the original album using a loop:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]
limit = 4

short_titles = []
for title, minutes in songs:
    if minutes <= limit:
        short_titles.append(title)
print(short_titles)  # ['Evangeline', 'Stick Season']

In a comprehension, the if goes after the for clause:

songs = [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)]
limit = 4

short_titles = [title for title, minutes in songs if minutes <= limit]

The condition can examine a changed value while the expression keeps the original. Which titles appear here, and will they be lowercase?

titles = ['Vienna', 'Evangeline', 'Stick Season']

print([title for title in titles if 'o' in title.lower()])  # ['Stick Season']

Because the condition runs first, it can exclude an input that the result expression cannot use.

A filter can skip zero before a division:

print([12 // minutes for minutes in [3, 0, 4] if minutes != 0])  # [4, 3]

Nested Comprehensions

A comprehension can produce lists as its items, giving a list of lists. An outer comprehension builds one result list, and each evaluation of its inner comprehension builds a list to put inside it. Keeping those groups preserves the connection between each input collection and its results.

To collect titles from several albums, start with two loops:

albums = [
    [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)],
    [('Evangeline', 6), ('Beautiful Things', 2)],
    [],
]

titles_by_album = []
for album in albums:
    album_titles = []
    for title, minutes in album:
        album_titles.append(title)
    titles_by_album.append(album_titles)
print(titles_by_album)  # [['Vienna', 'Evangeline', 'Stick Season'], ['Evangeline', 'Beautiful Things'], []]

Replace the inner loop first:

albums = [
    [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)],
    [('Evangeline', 6), ('Beautiful Things', 2)],
    [],
]

titles_by_album = []
for album in albums:
    album_titles = [title for title, minutes in album]
    titles_by_album.append(album_titles)

The outer loop also appends one value at a time, so its result expression can be the entire inner comprehension:

albums = [
    [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)],
    [('Evangeline', 6), ('Beautiful Things', 2)],
    [],
]

titles_by_album = [[title for title, minutes in album] for album in albums]

Add the duration filter to the inner comprehension:

albums = [
    [('Vienna', 5), ('Evangeline', 3), ('Stick Season', 4)],
    [('Evangeline', 6), ('Beautiful Things', 2)],
    [],
]
limit = 4

short_by_album = [
    [title for title, minutes in album if minutes <= limit]
    for album in albums
]
print(short_by_album)  # [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]

Change limit to 2 and predict the entire result, including empty lists. Run the comprehension to check your prediction.

Filtering inside an inner list changes that group’s contents. Filtering the outer list determines which groups remain. Empty lists are false in a condition, so if group selects nonempty groups, including [0].

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]

print([group for group in short_by_album if group])  # [['Evangeline', 'Stick Season'], ['Beautiful Things']]

An empty group can be useful in a count report: it preserves the album’s position and gives it a count of zero.

Flattening combines nested collections into a single sequence. Here we remove one level of nesting: each item from each inner list becomes an item in the result. Several for clauses inside one pair of comprehension brackets describe nested loops, with the leftmost for as the outermost loop. Both loops visit their inputs in order, preserving repeated values as well as their order. An empty group contributes no items.

The player needs one sequence of titles. Append each title directly to playlist:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]

playlist = []
for group in short_by_album:
    for title in group:
        playlist.append(title)
print(playlist)  # ['Evangeline', 'Stick Season', 'Beautiful Things']

The comprehension keeps the for clauses in the same order as the loops:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]

playlist = [title for group in short_by_album for title in group]

A filter immediately after the outer for selects whole groups:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]

print([title for group in short_by_album if len(group) >= 2 for title in group])
# ['Evangeline', 'Stick Season']

Expand that comprehension into loops and check where the if goes. Then add a second condition that keeps only titles containing 'o'.

An inner loop can visit a separate collection instead of a group selected by the outer loop. It then produces every combination: lists of lengths m and n produce m * n pairs. This differs from zip, which pairs items at matching positions.

Label every selected song for both walking and studying:

playlist = ['Evangeline', 'Stick Season', 'Beautiful Things']

pairs = [(title, label) for title in playlist for label in ['walk', 'study']]
print(len(pairs))  # 6
print(list(zip(playlist, ['walk', 'study'])))  # [('Evangeline', 'walk'), ('Stick Season', 'study')]

For each title, the nested loop visits both labels.

Dictionaries

A dictionary comprehension builds a dictionary by computing a key and a value for each iteration. Its form is {key_expression: value_expression for item in collection}, optionally followed by an if condition. A dictionary associates each distinct key with one value. If several iterations produce the same key, the last value assigned to that key is stored, without moving the key’s position.

Make the count report by pairing each album name with its selected titles:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]
album_names = ['Favorites', 'Live', 'Unsorted']

counts = {}
for name, group in zip(album_names, short_by_album):
    counts[name] = len(group)

A dictionary comprehension expresses that same loop:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]
album_names = ['Favorites', 'Live', 'Unsorted']

counts = {name: len(group) for name, group in zip(album_names, short_by_album)}
print(counts)  # {'Favorites': 2, 'Live': 1, 'Unsorted': 0}

If we instead use song titles as keys, studio and live versions of 'Evangeline' share a key:

versions = [('Evangeline', 3), ('Stick Season', 4), ('Evangeline', 6)]
print({title: minutes for title, minutes in versions})  # {'Evangeline': 6, 'Stick Season': 4}

A condition can select entries for the dictionary, just as it selects items for a list:

short_by_album = [['Evangeline', 'Stick Season'], ['Beautiful Things'], []]
album_names = ['Favorites', 'Live', 'Unsorted']

print({name: len(group) for name, group in zip(album_names, short_by_album) if group})
# {'Favorites': 2, 'Live': 1}

Print the playlist before the full count report:

playlist = ['Evangeline', 'Stick Season', 'Beautiful Things']
counts = {'Favorites': 2, 'Live': 1, 'Unsorted': 0}

for number, title in enumerate(playlist, start=1):
    print(number, title)
# 1 Evangeline
# 2 Stick Season
# 3 Beautiful Things
print(counts)  # {'Favorites': 2, 'Live': 1, 'Unsorted': 0}

Change the duration limit to 3 and rebuild short_by_album, playlist, and counts in that order. Predict which parts of the report will change, then try a limit that excludes every song. Should the full count report be empty or contain three zeros?