Lists in Action¶

Lab 9¶

  • oddities

Lab 10¶

  • average_positive
  • filter_infrequent
  • scale_to_unit
  • others?

Skinning the Cat 🐈¶

For the numbers 1 through 10:

  • multiply by 7
  • subtract 2
  • mod by 5
  • print the result
In [ ]:
def multiply(number):
    return number * 7

def subtract(number):
    return number - 2

def mod(number):
    return number % 5

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
    number = multiply(number)
    number = subtract(number)
    number = mod(number)
    print(number)
    
In [ ]:
def multiply(numbers):
    result = []
    for number in numbers:
        result.append(number * 7)
    return result

def subtract(numbers):
    result = []
    for number in numbers:
        result.append(number - 2)
    return result

def mod(numbers):
    result = []
    for number in numbers:
        result.append(number % 5)
    return result

def print_list(numbers):
    for number in numbers:
        print(number)
        
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = multiply(numbers)
numbers = subtract(numbers)
numbers = mod(numbers)
print_list(numbers)

NOTES

  • Compare the two approaches: itemwise and batch
    • The first uses fewer lines of code. The for loop is written only once
    • The first operates on single values; the second operates on lists
  • When working with a collection of values, either strategy could be valid
    • Sometimes one strategy is preferred over the other

👩🏾‍🎨 We love lists of numbers¶

For the numbers 1 through 10:

  • multiply by 7
  • subtract the minimum
  • print the result

🧐
</br>

When the sequence of operations only depends on each individual item, one at a time, we can use the itemwise approach.

When any of the operations relies on seeing all of the items at the same time, we need the batch approach.