Day 25 - Transition to Python 2
Skills: None
Pre-reading: 9.1.6, 9.1.7
Intro (10 mins)
- Today we explore how to create and process lists in Python, and compare with Pyret.
- In Python, lists are created with square brackets, e.g.:
fruits = ["apple", "banana", "cherry", "date"]
- Python has built-in functions like
filter
andmap
for processing lists, 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
lambda
in Python (single expression only). - Dataclasses: Python's
@dataclass
decorator allows you to define structured data types, similar to structured data using Pyret'sdata
definitions (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)
- Create a list of integers from 1 to 10.
- Write a expression using
map
that produces a list of their squares. - Design a function
all_even(nums: list) -> list
that returns a list of all even numbers from the input list. - Design a function
capitalize_all(words: list) -> list
that returns a list of all words capitalized. - Use
map
andlambda
to 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 the error. - Define a
@dataclass
calledBook
with fieldstitle
(str),author
(str), andpages
(int). - Design a function
long_books(books: list) -> list
that returns a list of titles of books with more than 300 pages. Remember to always include docstring, type signature, and pytest tests. - Create a list of
Book
instances and uselong_books
to filter them. - 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)
- Python lists use square brackets and require wrapping
map
/filter
results withlist()
. - Dataclasses provide a way to define structured data, similar to Pyret's
data
.