Skip to main content

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)​

Level: start your file with #level intermediate (see Language Levels).

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.:
    #level intermediate

    fruits = ["apple", "banana", "cherry", "date"]
  • Python has built-in functions like filter and map for processing lists (just like you learned in Pyret, in Day 14), but you must wrap their results with list():
    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 lambda in Python -- but these are more restricted than Pyret's lam, as the body can be a single expression only (i.e., you cannot have an if, for, variable assignment, etc, inside a lambda).

Dataclasses​

  • Python's @dataclass decorator, combined with the class feature, allows you to define structured data types, similar to structured data using a single variant with Pyret's data definitions (conditional data is more complicated, and not covered here). Example:
    @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.

  1. Create a list of integers from 1 to 10.
  2. Write an expression using map that produces a list of their squares.
  3. Design a function all_even(nums: list) -> list that returns a list of all even numbers from the input list.
  4. Design a function capitalize_all(words: list) -> list that returns a list of all words capitalized.
  5. Use map and lambda to produce a list of the lengths of each word in ["hello", "world", "python"].
  6. What happens if you forget to wrap the result in list()? Try it and note what you see.
  7. Define a @dataclass called Book with fields title (str), author (str), and pages (int).
  8. Design a function long_books(books: list) -> list that returns a list of titles of books with more than 300 pages. Include a docstring, type annotations, and tests in the same file.
  9. Create a list of Book instances and use long_books to filter them.
  10. Design a function filter_by_author(books: list, author: str) -> list that 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.