Quick Stats
Completed
0
Time Spent
0m
Streak
0
User
Lists, Dicts, and Comprehensions
The workhorses of data code.
The workhorses of data code
You met lists and dicts already; now let's use them like a practitioner, because nearly everything you do with data is reshaping these two structures. A loaded CSV becomes a list of dicts; a model's output is a dict; a batch of inputs is a list. Fluency here pays off every single day.
Doing more with lists
Lists are ordered and flexible:
nums = [4, 1, 7, 3]
nums.append(9) # add to the end -> [4, 1, 7, 3, 9]
nums.sort() # in place -> [1, 3, 4, 7, 9]
print(nums[0], nums[-1]) # first and last: 1 9
print(nums[1:3]) # a slice: [3, 4]
print(len(nums)) # how many: 5Slicing ([start:stop]) and indexing — including negative indexes from the end — come up constantly.
Doing more with dicts
Dicts map keys to values, ideal for records:
person = {"name": "Ada", "age": 36}
person["email"] = "ada@example.com" # add a field
print(person.get("phone", "n/a")) # safe lookup with a default
for key, value in person.items(): # walk every pair
print(key, "=", value).get() saves you from crashes when a key might be missing — a frequent real-world need.
Comprehensions: the Pythonic loop
A list comprehension builds a new list from an old one in one readable line:
squares = [n * n for n in range(5)] # [0, 1, 4, 9, 16]
evens = [n for n in nums if n % 2 == 0] # filter while you buildIt's the same as a for loop with .append(), but shorter and clearer — and you'll see it everywhere in data and AI code.
Lists hold sequences, dicts hold labeled records, and comprehensions transform them in a line. Get fluent with these and most "how do I reshape this data?" questions answer themselves.
Try this: Start with a list of numbers and write one comprehension that keeps only the even ones, doubled. Then build a dict that counts how many times each word appears in a sentence. Filter/transform a list, tally into a dict — these two patterns recur in almost every data task.