Skip to content

Nov 05: Prac5, Lists of Lists

Learning Objectives

After today's class, you should be able to:

  • Write code that reads or writes a file using a with statement.
  • Explain the syntax and meaning of a list/set/dict comprehension.

Announcements

  • Code: PA 2
    • Part A due TODAY!
    • Part B due Tue, Nov 11
  • Read Week 12 – ideally:
    • 1st half before Friday
    • 2nd half before Monday

File I/O Debrief

[5 min]

Refer to Friday's activity

  • Question 3: Write a file
    with open("lines.txt", "w") as file:
        for i in range(1, 101):
            file.write(f"Line #{i}\n")
    
  • Question 14: Read a file
    with open("names.txt") as file:
        for line in file:
            words = line.split()
            print(words[1])
    

Comprehensions

[10 min]

A concise way to build a new list, set, or dictionary

List comprehension:

new_list = [expression for item in iterable if condition]
Set comprehension:
new_set = {expression for item in iterable if condition}
Dict comprehension:
new_dict = {key_exp: value_exp for item in iterable if condition}

Example 1

  • Building a simple list:
    squares = []
    for x in range(10):
        squares.append(x ** 2)
    
  • Can be rewritten as:
    squares = [x ** 2 for x in range(10)]
    

Example 2

  • Adding an if statement:
    squares = []
    for x in range(10):
        if x % 2 == 0:
            squares.append(x ** 2)
    
  • Can be rewritten as:
    [x ** 2 for x in range(10) if x % 2 == 0]
    

Example 3

  • Practice Quiz 4:
    def limit_letters(counts: dict, limit: int) -> set:
        """Get letters that don't exceed a count limit."""
    
        return {letter for letter in counts if counts[letter] <= limit}
    
  • Actual Quiz 4:
    def big_cats(data: dict, heavy: int) -> list:
        """Get cats whose weight is greater than heavy."""
    
        return [cat for cat in data if data[cat] > heavy]
    

Lists of Lists

[10 min]

Data types from PA 2:

  • A "cell" is a list of strings:
    Cell = list[str]
    
  • A "grid" is a list of cells:
    Grid = list[Cell]
    

In other words, a grid is a list of list of strings.

2D lists have two indexes:

  • grid[n][0] means "letter of nth cell"
  • grid[n][1] means "color of nth cell"

Practice Quiz 5

[25 min]

Topics: Strings (PA1-B) and File I/O (PA2-A)

  • 1st sheet: "written potion"
    • Turn off monitor during written portion
  • 2nd sheet: "coding potion"
    • You must use Thonny (not VS Code)
    • Do not turn off recording; just log out