Day 25 - Lists and Dataclasses in Python
Date: November 12, 2026
⚠️Homework
Homework 9 due November 15, 2026
Skills: 8
Pre-reading: 9.1.6, 9.1.7
Supplementary Videos
Lists and Dataclasses in Python
Intro (20 mins)
Yesterday we set up Python in VSCode (using the PLL Extension) and wrote functions, conditionals, and tests. Today we look at lists and structured data.
Creating lists
- In Python, lists are created with square brackets, e.g.:
fruits = ["apple", "banana", "cherry", "date"] - Python has built-in functions like
filterandmapfor processing lists (just like you learned in Pyret, in Day 14), but you must wrap their results withlist():fruits_with_a = list(filter(lambda f: "a" in f, fruits))
# ["apple", "banana", "date"]
fruits_upper = list(map(lambda f: f.upper(), fruits))
# ["APPLE", "BANANA", "CHERRY", "DATE"] - Anonymous functions use
lambdain Python -- but these are more restricted than Pyret'slam, as the body can be a single expression only (i.e., you cannot have anif,for, variable assignment, etc, inside alambda).
Dataclasses
- Python's
@dataclassdecorator, combined with theclassfeature, allows you to define structured data types, similar to structured data using a single variant with Pyret'sdatadefinitions (conditional data is more complicated, and not covered here). Example:from dataclasses import dataclass
@dataclass
class Fruit:
name: str
color: str
Class Exercises (35 mins)
Remember: tests go in the same file as the functions they test. Click PLL: Run Python File to run them.
- Create a list of integers from 1 to 10.
- Write an expression using
mapthat produces a list of their squares. - Design a function
all_even(nums: list) -> listthat returns a list of all even numbers from the input list. - Design a function
capitalize_all(words: list) -> listthat returns a list of all words capitalized. - Use
mapandlambdato produce a list of the lengths of each word in["hello", "world", "python"]. - What happens if you forget to wrap the result in
list()? Try it and note what you see. - Define a
@dataclasscalledBookwith fieldstitle(str),author(str), andpages(int). - Design a function
long_books(books: list) -> listthat returns a list of titles of books with more than 300 pages. Include a docstring, type annotations, and tests in the same file. - Create a list of
Bookinstances and uselong_booksto filter them. - Design a function
filter_by_author(books: list, author: str) -> listthat returns a list of titles of books by the given author.
Wrap-up (5 mins)
- Pyret and Python share many aspects, but differ in some ways as well.