comprehensions - stanford university€¦ · everyday python life after cs106ap! day 1! graphics...

130
Comprehensions CS106AP Lecture 24

Upload: others

Post on 05-Oct-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

ComprehensionsCS106AP Lecture 24

Page 2: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

RoadmapProgramming Basics

The Console Images

Data structures

MidtermGraphics

Object-Oriented Programming

Everyday Python

Life after CS106AP!

Day 1!

Page 3: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Graphics

Images

The Console

Data structures

Midterm

Programming Basics

Roadmap

Life after CS106AP!

Day 1!

Object-Oriented Programming

Everyday Python

Tuples

List Comp.

Lambdas

Internet

Computers

Life After

Final Exam

Page 4: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Today’s questions

How can we write better loops?

What tools do we have for developing code and analyzing data?

Page 5: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Today’s topics

1. Review

2. List and Dict Comprehensions

3. Jupyter Notebooks

4. What’s next?

Page 6: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Review

Page 7: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples

Page 8: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

What is a tuple?

(‘a’, ‘b’, ‘c’)

(‘karel’, 1)

(‘simba’, ‘lion’, 25)

TupleAn immutable data type for storing values in an ordered

linear collection.

Definition

like a list, but written with parentheses ( ) instead of [ ]

Page 9: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples vs. Lists

● len(), print()● slicing, indexing● in● foreach loops● concatenation (creates new)● immutable

○ can’t add elements○ can’t remove elements

● len(), print()● slicing, indexing● in● foreach loops● concatenation (creates new)● mutable

○ append(), extend()○ pop(), remove()

Page 10: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples don’t support item assignment

>>> tup = (‘apple’, 0.79, ‘WA’)

>>> tup[0]

‘apple’

>>> tup[2] = ‘CA’

TypeError

You can index in to view the elements

You can’t index in to set one of the elements

Page 11: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuple packing/unpacking

>>> tup = (‘apple’, 0.79, ‘WA’)

>>> tup

(‘apple’, 0.79, ‘WA’)

>>> food, price, location = tup

>>> price

0.79

unpack tuple contents into other variables

Page 12: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Assigning multiple variables simultaneously

>>> a, b = 1, 2

>>> a

1

>>> b

2

packs 1, 2 into tuple and unpacks into variables b, a

Note: length of left-hand side must = length of right-hand side!

Page 13: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples for swapping variables

>>> a, b = 1, 2

>>> b, a = a, b

>>> b

1

>>> a

2

packs a, b into tuple and unpacks into variables b, a

Page 14: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples vs. Lists

● fixed number of elements

● know # ahead of time

● sometimes different types

● unbound number of elements

● sometimes large number

● usually all elements are the same type

not enforced by Python but good style

Page 15: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples as return values

def animal_min_feedings(animal_dict):

name, min_feedings = None, float(‘inf’)

for animal, num_feedings in animal_dict.items():

if num_feedings < min_feedings:

name, min_feedings = animal, num_feedings

return name, min_feedings

actually a tuple!

Page 16: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples as return values

def animal_min_feedings(animal_dict):

name, min_feedings = None, float(‘inf’)

for animal, num_feedings in animal_dict.items():

if num_feedings < min_feedings:

name, min_feedings = animal, num_feedings

return name, min_feedings packs name, min_feedingsinto a tuple and returns!

Page 17: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Tuples as return values

def print_hungriest_animal(filename):

animal_dict = get_animal_feedings(filename)

animal, num = animal_min_feedings(animal_dict)

print(animal, ‘eats’, num, ‘times a day.’)

unpacks name, min_feedings tuple into two variables

Page 18: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Sorting lists with tuples

>>> fruit = [(‘mango’, 3), (‘apple’, 6), (‘lychee’, 1), (‘apricot’, 10)]

>>> sorted(fruit)

[(‘apple’, 6), (‘apricot’, 10), (‘lychee’, 1), (‘mango’, 3)]

sorts by the first element in each tuple

Page 19: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

How can we write better loops?

Page 20: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares

● Say you have a list of numbers and you want a list of those numbers’

squares.

Page 21: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares

● Say you have a list of numbers and you want a list of those numbers’

squares.

[1, 3, 6, 7] --> [1, 9, 36, 49]

Page 22: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares

● Say you have a list of numbers and you want a list of those numbers’

squares.

[1, 3, 6, 7] --> [1, 9, 36, 49]

● How would you produce the output list?

Page 23: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #1

Page 24: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #1

# [1, 3, 6, 7] --> [1, 9, 36, 49]

Page 25: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #1

# [1, 3, 6, 7] --> [1, 9, 36, 49]def get_squared(nums): result = [] for n in nums: result.append(n ** 2) return result

Page 26: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #1

# [1, 3, 6, 7] --> [1, 9, 36, 49]def get_squared(nums): result = [] for n in nums: result.append(n ** 2) return result

nums = [1, 3, 6, 7]squared_numbers = get_squared(nums)

Page 27: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #2

Page 28: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #2

# [1, 3, 6, 7] --> [1, 9, 36, 49]

Page 29: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #2

# [1, 3, 6, 7] --> [1, 9, 36, 49]

nums = [1, 3, 6, 7]

Page 30: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #2

# [1, 3, 6, 7] --> [1, 9, 36, 49]

nums = [1, 3, 6, 7]squared_nums = [n ** 2 for n in nums]

Page 31: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of squares - Attempt #2

# [1, 3, 6, 7] --> [1, 9, 36, 49]

nums = [1, 3, 6, 7]squared_nums = [n ** 2 for n in nums]

this is a list comprehension!

Page 32: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

List ComprehensionA way to create a list

based on existing lists

Definition

Page 33: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

List ComprehensionA way to create a list

based on existing lists

Definitionexpression

Page 34: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

List ComprehensionA way to create a list

based on existing lists

Definitionexpression item

Page 35: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

List ComprehensionA way to create a list

based on existing lists

Definitionexpression item

list

Page 36: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

List ComprehensionA way to create a list

based on existing lists

Definition

Page 37: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

● Reuses syntax from other features:

List ComprehensionA way to create a list

based on existing lists

Definition

Page 38: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

● Reuses syntax from other features:○ [] to create new list

List ComprehensionA way to create a list

based on existing lists

Definition

Page 39: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

List Comprehensions

[n ** 2 for n in nums]

● Reuses syntax from other features:○ [] to create new list○ foreach loop over other list

List ComprehensionA way to create a list

based on existing lists

Definition

Page 40: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

Page 41: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

● Say you have a list of strings with random casing and you want them to be lowercase.

Page 42: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

● Say you have a list of strings with random casing and you want them to be lowercase.

in: [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

out: [‘sonja’, ‘nicholas’, ‘kylie’]

Page 43: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

● Say you have a list of strings with random casing and you want them to be lowercase.

in: [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

out: [‘sonja’, ‘nicholas’, ‘kylie’]

● How would you produce the output list?

Page 44: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

Page 45: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

Page 46: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

lower_strings = [s.lower() for s in strings]

Page 47: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

lower_strings = [s.lower() for s in strings]

expression item list

Page 48: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of lowercase strings

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

lower_strings = [s.lower() for s in strings]

Note: a list comprehension creates a new list and doesn’t modify the old list

expression item list

Page 49: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

Page 50: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

● Say you have a list of strings with random casing and you want them to have the first letter uppercase and other letters lowercase.

Page 51: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

● Say you have a list of strings with random casing and you want them to have the first letter uppercase and other letters lowercase.

in: [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

out: [‘Sonja’, ‘Nicholas’, ‘Kylie’]

Page 52: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

● Say you have a list of strings with random casing and you want them to have the first letter uppercase and other letters lowercase.

in: [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

out: [‘Sonja’, ‘Nicholas’, ‘Kylie’]

Think/Pair/Share:How would you produce the

output list?

Page 53: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

Page 54: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

Page 55: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [s[0].upper() + s[1:].lower() for s in strings]

Page 56: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [s[0].upper() + s[1:].lower() for s in strings]

expression

Page 57: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [s[0].upper() + s[1:].lower() for s in strings]

expression item

Page 58: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of formatted names

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [s[0].upper() + s[1:].lower() for s in strings]

expression item list

Page 59: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Combining functions with list comprehensions

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [s[0].upper() + s[1:].lower() for s in strings]

expression can be decomposed out into a function!

Page 60: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Combining functions with list comprehensions

def name_case(s):

return s[0].upper() + s[1:].lower()

Page 61: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Combining functions with list comprehensions

def name_case(s):

return s[0].upper() + s[1:].lower()

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

Page 62: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Combining functions with list comprehensions

def name_case(s):

return s[0].upper() + s[1:].lower()

strings = [‘SOnja’, ‘nicHOLAs’, ‘KYLiE’]

name_strings = [name_case(s) for s in strings]

Page 63: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

● Say you have a list of strings. Return a list of tuples where the first elem is the string and the second elem is the length of the string.

Page 64: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

● Say you have a list of strings. Return a list of tuples where the first elem is the string and the second elem is the length of the string.

in: [‘I’, ‘love’, ‘CS106AP’]

out: [(‘I’, 1), (‘love’, 4), (‘CS106AP’, 7)]

Page 65: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

● Say you have a list of strings. Return a list of tuples where the first elem is the string and the second elem is the length of the string.

in: [‘I’, ‘love’, ‘CS106AP’]

out: [(‘I’, 1), (‘love’, 4), (‘CS106AP’, 7)]

Think/Pair/Share:How would you produce the

output list?

Page 66: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

Page 67: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

strings = [‘I’, ‘love’, ‘CS106AP’]

Page 68: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

strings = [‘I’, ‘love’, ‘CS106AP’]

tuples = [(s, len(s)) for s in strings]

Page 69: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

strings = [‘I’, ‘love’, ‘CS106AP’]

tuples = [(s, len(s)) for s in strings]

expression

Page 70: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

strings = [‘I’, ‘love’, ‘CS106AP’]

tuples = [(s, len(s)) for s in strings]

expression item

Page 71: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: getting a list of tuples

strings = [‘I’, ‘love’, ‘CS106AP’]

tuples = [(s, len(s)) for s in strings]

expression item list

Page 72: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> nums = [4, 23, 9, 18, 63, 42]

Page 73: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> nums = [4, 23, 9, 18, 63, 42]what if I only want even numbers?

Page 74: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> nums = [4, 23, 9, 18, 63, 42]

>>> even_nums = [n for n in nums if n % 2 == 0]

Page 75: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> nums = [4, 23, 9, 18, 63, 42]

>>> even_nums = [n for n in nums if n % 2 == 0]

>>> even_nums

Page 76: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> nums = [4, 23, 9, 18, 63, 42]

>>> even_nums = [n for n in nums if n % 2 == 0]

>>> even_nums

[4, 18, 42]

Page 77: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

Page 78: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

Page 79: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

[n for n in nums if n % 2 == 0]

Page 80: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

[n for n in nums if n % 2 == 0]

expression

Page 81: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

[n for n in nums if n % 2 == 0]

expression item

Page 82: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

[n for n in nums if n % 2 == 0]

expression item list

Page 83: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

● You can add a condition for additional “filtering”

[expression for item in list if condition]

[n for n in nums if n % 2 == 0]

expression item list condition

Page 84: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> strings = [‘sonja’, ‘kylie’, ‘nick’]

Page 85: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> strings = [‘sonja’, ‘kylie’, ‘nick’]

what if I don’t want strings that start with ‘s’?

Page 86: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> strings = [‘sonja’, ‘kylie’, ‘nick’]

>>> no_s_strings = [s for s in strings if s[0].lower() != ‘s’]

Page 87: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> strings = [‘sonja’, ‘kylie’, ‘nick’]

>>> no_s_strings = [s for s in strings if s[0].lower() != ‘s’]

>>> no_s_strings

Page 88: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> strings = [‘sonja’, ‘kylie’, ‘nick’]

>>> no_s_strings = [s for s in strings if s[0].lower() != ‘s’]

>>> no_s_strings

[‘kylie’, ‘nick’]

Page 89: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> song = [‘the’, ‘wheels’, ‘on’, ‘the’, ‘bus, ‘go’,‘round’, ‘and’, ‘round’]

Page 90: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> song = [‘the’, ‘wheels’, ‘on’, ‘the’, ‘bus, ‘go’,‘round’, ‘and’, ‘round’]

>>> round_words = [‘wheels’, ‘round’, ‘circle’]

Page 91: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> song = [‘the’, ‘wheels’, ‘on’, ‘the’, ‘bus, ‘go’,‘round’, ‘and’, ‘round’]

>>> round_words = [‘wheels’, ‘round’, ‘circle’]

>>> not_round_song = [word for word in song if word not in round_words]

Page 92: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> song = [‘the’, ‘wheels’, ‘on’, ‘the’, ‘bus, ‘go’,‘round’, ‘and’, ‘round’]

>>> round_words = [‘wheels’, ‘round’, ‘circle’]

>>> not_round_song = [word for word in song if word not in round_words]

>>> not_round_song

Page 93: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Conditions in list comprehensions

>>> song = [‘the’, ‘wheels’, ‘on’, ‘the’, ‘bus, ‘go’,‘round’, ‘and’, ‘round’]

>>> round_words = [‘wheels’, ‘round’, ‘circle’]

>>> not_round_song = [word for word in song if word not in round_words]

>>> not_round_song

[‘the’, ‘on’, ‘the’, ‘bus, ‘go’,‘and’]

Page 94: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Why list comprehensions?

Page 95: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Why list comprehensions?

● They’re more concise

Page 96: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Why list comprehensions?

● They’re more concise

● They’re faster

Page 97: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Why list comprehensions?

● They’re more concise

● They’re faster

● They’re Pythonic

Page 98: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

When to not use list comprehensions

Page 99: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

When to not use list comprehensions

● When you need more than one condition

Page 100: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

When to not use list comprehensions

● When you need more than one condition

● When the expression is complex

Page 101: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

When to not use list comprehensions

● When you need more than one condition

● When the expression is complex

○ Break it out into a separate function!

Page 102: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dictionary Comprehensions

Page 103: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: updating all the values in a dict

● Say you have a dictionary of strings to ints, and you want to double the values in the dictionary.

Page 104: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: updating all the values in a dict

● Say you have a dictionary of strings to ints, and you want to double the values in the dictionary.

in: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

out: {‘a’: 2, ‘b’: 4, ‘c’: 6, ‘d’: 8}

Page 105: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: updating all the values in a dict

● Say you have a dictionary of strings to ints, and you want to double the values in the dictionary.

in: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

out: {‘a’: 2, ‘b’: 4, ‘c’: 6, ‘d’: 8}

● How would you produce the output dictionary?

Page 106: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

Page 107: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

doubled = {k:2*v for (k, v) in d.items()}

Page 108: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

doubled = {k:2*v for (k, v) in d.items()}

new key

Page 109: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

doubled = {k:2*v for (k, v) in d.items()}

new key new value

Page 110: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

doubled = {k:2*v for (k, v) in d.items()}

new key itemnew value

Page 111: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

doubled = {k:2*v for (k, v) in d.items()}

new key item iterablenew value

Page 112: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: reversing the keys and values in a dict

● Make the keys the values and the values the keys!

in: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

out: {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

Think/Pair/Share:How would you produce the

output dictionary?

Page 113: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Problem: reversing the keys and values in a dict

● Make the keys the values and the values the keys!

in: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

out: {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

Think/Pair/Share:How would you produce the

output dictionary?

doubled = {k:2*v for (k, v) in d.items()}

Page 114: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

Page 115: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

flipped = {v:k for (k, v) in d.items()}

Page 116: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

flipped = {v:k for (k, v) in d.items()}

new key

Page 117: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

flipped = {v:k for (k, v) in d.items()}

new key new value

Page 118: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

flipped = {v:k for (k, v) in d.items()}

new key itemnew value

Page 119: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Dict Comprehensions

d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

flipped = {v:k for (k, v) in d.items()}

new key item iterablenew value

Page 120: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

What tools do we have for developing code and analyzing

data?

Page 121: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebooks

Page 122: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook

● Interactive “notebook” where you can run parts of code

Page 123: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook

● Interactive “notebook” where you can run parts of code

○ Can develop code step-by-step

Page 124: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook

● Interactive “notebook” where you can run parts of code

○ Can develop code step-by-step

○ Great for data analysis

Page 125: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook

● Interactive “notebook” where you can run parts of code

○ Can develop code step-by-step

○ Great for data analysis

● Built on top of regular Python code

Page 126: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook Setup

$ python3 -m pip install jupyter

Page 127: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Jupyter Notebook: Investigating California Air Quality

Page 128: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

What’s next?

Page 129: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Graphics

Images

The Console

Data structures

Midterm

Programming Basics

Roadmap

Life after CS106AP!

Day 1!

Object-Oriented Programming

Everyday Python

Tuples

List Comp.

Lambdas

Internet

Computers

Life After

Final Exam

Page 130: Comprehensions - Stanford University€¦ · Everyday Python Life after CS106AP! Day 1! Graphics The Console Images Data structures Midterm Programming Basics ... List and Dict Comprehensions

Lambdas and Custom Sort

● How can we customize our sorting?