We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

List Comprehensions

In data work, you're constantly building new lists. Say you have a list of songs:

tracks = [
    {"track_id": "T-100", "plays": 2},
    {"track_id": "T-101", "plays": 5},
    {"track_id": "T-102", "plays": 4},
]

And you want a new list with just the number of "plays" for each track. You can do that with a normal for loop:

play_counts = []
for track in tracks:
    play_counts.append(track["plays"])
print(play_counts)
# [2, 5, 4]

It works, but it's a lot of boilerplate. Python gives us a shorter way with list comprehensions.

play_counts = [track["plays"] for track in tracks]
print(play_counts)
# [2, 5, 4]

It says:

  • take track["plays"]
  • for each track
  • in the tracks list
  • and give me a new list with those values (play_counts)

The syntax is:

[expression for item in iterable]

And if you want to filter as well:

[expression for item in iterable if condition]

For example:

long_play_counts = [track["plays"] for track in tracks if track["plays"] > 3]
print(long_play_counts)
# [5, 4]

Not only are comprehensions more concise, but they're also often more performant than a normal loop because the Python interpreter can optimize them more easily under the hood.

Just because you can cram a bunch of logic into one massive comprehension doesn't mean you should. If it's too cursed, stick to a normal loop.

Assignment

SnackStack's support team exports appliance support tickets as a list of dictionaries.

Complete the get_escalated_ticket_ids function. It accepts a list of ticket dictionaries and returns a list of ticket IDs. Use a list comprehension to create and return a list that: