Day 26 - Transition to Python 2
Creating and Processing Lists in Python
1. Introduction (10 minutes)
- Overview:
- Recap that in Pyret we have used both recursion and for‑each loops to process lists.
- Today we show how Python’s handles lists.
- Learning Goals:
- Learn how to create lists in Python.
- Explore built‑in list functions such as filter, map, and length.
- Contrast Python’s style with Pyret’s
for each
loops and recursive definitions.
2. Creating and Processing Lists
-
Creating Lists:
- Python Example:
fruits = ["apple", "banana", "cherry", "date"]
- Python Example:
-
Using Filter and Map:
-
Example 1: Filtering words containing the letter “a”
fruits_with_a = list(filter(lambda f: "a" in f, fruits))
# Expected: ["apple", "banana", "date"] -
Example 2: Mapping to uppercase
fruits_upper = list(map(lambda f: f.upper(), fruits))
# Expected: ["APPLE", "BANANA", "CHERRY", "DATE"] -
NOTE:
map
andfilter
in Python don't return lists directly, but the return type (a more complicated abstraction called an iterator) can be converted to a list with the functionlist
, as we've done above.
-
-
Interactive Exercise:
- Ask students: “Write an expression that produces a list of the lengths of each fruit name.”
- Expected answer:
fruit_lengths = list(map(len, fruits))
# Expected: [5, 6, 6, 4]
-
Comparison with Pyret:
- Briefly review that in Pyret, lists are created with
[list: ...]
and functions like filter and map directly return lists.
- Briefly review that in Pyret, lists are created with
3. Test Cases for List Functions in Python
- Example Function –
all_long_words
:- Task: Write a function that takes a list of strings and returns a list of words with more than 5 letters.
- Python Code:
def all_long_words(word_list: list) -> list:
return list(filter(lambda wd: len(wd) > 5, word_list)) - NOTE:
lambda
used for anonymous functions, instead oflam
, but no parenthesis. Alsolambda
in python can only be a single expression, unlike Pyret.
- Test Cases Using pytest:
def test_all_long_words():
words = ["sky", "ocean", "mountain", "river"]
assert all_long_words(words) == ["ocean", "mountain"] - Do Now:
- Ask: “What happens if you forget to wrap filter with list()? (Discuss error messages like ‘object of type 'filter' has no len()’.)”
4. Wrap-Up (10 minutes)
- Recap Key Points:
- How lists are defined in Python versus Pyret.
- Using filter and map in Python requires wrapping the result in list.
- Notational differences: square brackets vs.
[list: …]
, lambda usage, etc.
- Exit Ticket:
- Students write a brief explanation (2–3 sentences) comparing Python’s list processing functions to Pyret’s methods.
- Preview Next Lecture:
- “Next, we’ll explore how to traverse lists using Python’s for loops—and we’ll contrast that with Pyret’s recursive and for‑each loop approaches.”