

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Welcome to Pandas
incomplete
2: Data Types
incomplete
3: Data Analytics Workflow
incomplete
4: Dates and Times
incomplete
5: Datetime Math
incomplete
6: Comparing Dates
incomplete
7: List Comprehensions
incomplete
8: Dictionary Comprehensions
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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:
track["plays"]tracktracks listplay_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.
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: