Skip to content
Snippets Groups Projects
Commit 50603bb0 authored by Andy Kuemmel's avatar Andy Kuemmel
Browse files

Update f22/andy_lec_notes/lec20_Oct24_Tuples/lec20_tuples_complete.ipynb,...

Update f22/andy_lec_notes/lec20_Oct24_Tuples/lec20_tuples_complete.ipynb, f22/andy_lec_notes/lec20_Oct24_Tuples/lec20_tuples_template.ipynb, f22/andy_lec_notes/lec20_Oct24_Tuples/readme.md
Deleted f22/andy_lec_notes/lec_20/lec20_tuples_850.ipynb
parent 1fdc3f46
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmups
%% Cell type:code id: tags:
``` python
from collections import namedtuple
# we are going to learn about this today !
```
%% Cell type:code id: tags:
``` python
# Warmup 1a:
thing1 = {}
type(thing1)
```
%% Output
dict
%% Cell type:code id: tags:
``` python
# Warmup 1b: How do you make an empty set?
thing2 = set()
print(type(thing2))
```
%% Output
<class 'set'>
%% Cell type:code id: tags:
``` python
# Warmup 1c:
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## October 25: Objects and Tuples
Learning Objectives:
- Explain the difference between objects vs references, and stack vs heap.
- Determine the side effects that occur when modifying object parameters.
- Use tuples to store immutable sequences of values.
- Use namedtuple (immutable) to store user-defined data objects.
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
### Explain the difference between objects vs references, and stack vs heap.
- check out the slides starting at slide ____
- try some of that code in Python Tutor
%% Cell type:markdown id: tags:
### Determine the side effects that occur when modifying parameters.
%% Cell type:code id: tags:
``` python
# example 5a: try this in Python tutor
def f(x):
x *= 3
print("f:", x)
num = 10
f(num)
print("after:", num)
# takeaway: what happens when a parameter is reassigned?
# your answer: Python makes a new object,
# the reference changes to the new object
```
%% Output
f: 30
after: 10
%% Cell type:code id: tags:
``` python
# example 5b: try in Python Tutor
def f(items):
items.append("!!!")
print("f:", items)
words = ['hello', 'world']
f(words)
print("after:", words)
# takeaway: what happens when a list parameter is mutated ?
# your answer: we don't make a new object, the reference is the same
```
%% Output
f: ['hello', 'world', '!!!']
after: ['hello', 'world', '!!!']
%% Cell type:code id: tags:
``` python
# example 5c: try in Python Tutor
def f(items):
items = items + ["!!!"]
print("f:", items)
words = ['hello', 'world']
f(words)
print("after:", words)
# takeaway: what happens when a list parameter is reassigned ?
# your answer: a new object is made, the reference changes
```
%% Output
f: ['hello', 'world', '!!!']
after: ['hello', 'world']
%% Cell type:code id: tags:
``` python
# example 5d: try in Python Tutor
def first(items):
return items[0]
def smallest(items):
items.sort()
return items[0]
numbers = [4,5,3,2,1]
print("first:", first(numbers))
print("smallest:", smallest(numbers))
print("first:", first(numbers))
# takeaway: what happens when a list parameter is sorted "in place" using .sort() ?
# your answer: sort() mutates a list, changes remain
```
%% Output
first: 4
smallest: 1
first: 1
%% Cell type:code id: tags:
``` python
# example 5e: try in Python Tutor
def first(items):
return items[0]
def smallest(items):
items = sorted(items)
return items[0]
numbers = [4,5,3,2,1]
print("first:", first(numbers))
print("smallest:", smallest(numbers))
print("first:", first(numbers))
# takeaway: what happens when a list parameter is sorted using sorted()?
# your answer: sorted makes a new list, that is reassignment
```
%% Output
first: 4
smallest: 1
first: 4
%% Cell type:markdown id: tags:
### In summary, write one good thing and one bad thing about lists being mutable
%% Cell type:code id: tags:
``` python
# Good thing:
#
```
%% Cell type:code id: tags:
``` python
# Bad thing:
#
```
%% Cell type:markdown id: tags:
### Use tuples to store immutable sequences of values.
Check out the slides about tuples
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Tuples are like lists BUT are IMMUTABLE
# practice with tuples
scores = [32, 55, 72, 91] # a list is mutable
coordinates = (-3, 4, 7) # a tuple is not mutable
scores_tuple = tuple(scores) # you can convert a list into a tuple
print(scores_tuple)
# Question: Can tuples be sorted?
# Discuss with your neighbor
# coordinates.sort() # tuples are immutable
new_tuple = tuple(sorted(coordinates)) # sorted makes a new list
print(new_tuple)
# Takeaway: Write a note to yourself about tuples
```
%% Output
(32, 55, 72, 91)
(-3, 4, 7)
%% Cell type:code id: tags:
``` python
# show that scores is mutable
scores.append(17)
print(scores)
```
%% Output
[32, 55, 72, 91, 17]
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# give an example of reassignment of 'coordinates'
scores[0] = 1
scores
```
%% Output
[1, 55, 72, 91, 17]
%% Cell type:code id: tags:
``` python
# show that tuples are immutable
coordinates[0] = 1
print(coordinates)
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-567a460f4882> in <module>
1 # show that tuples are immutable
----> 2 coordinates[0] = 1
3
4 print(coordinates)
TypeError: 'tuple' object does not support item assignment
%% Cell type:markdown id: tags:
### Tuples Reference: https://www.w3schools.com/python/python_tuples.asp
%% Cell type:code id: tags:
``` python
# Why use tuples?
# 1. helps us accidentally avoid changing our dataset
# 2. we can avoid the problems we had above with changes in functions
```
%% Cell type:code id: tags:
``` python
# Why use tuples?
# 3. keys in dictionaries must be immutable types
# Fails with TypeError
buildings = {
[0,0]: "Comp Sci",
[0,2]: "Psychology",
[4,0]: "Noland",
[1,8]: "Van Vleck" }
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-266ce4d9d9c7> in <module>
4
5 # Fails with TypeError
----> 6 buildings = {
7 [0,0]: "Comp Sci",
8 [0,2]: "Psychology",
TypeError: unhashable type: 'list'
%% Cell type:code id: tags:
``` python
# Dictionary with tuples as keys
buildings = {
(0,0): "Comp Sci",
(0,2): "Psychology",
(4,0): "Noland",
(1,8): "Van Vleck" }
# find the name of the building at coordinate (4,0)
```
%% Output
{(0, 0): 'Comp Sci',
(0, 2): 'Psychology',
(4, 0): 'Noland',
(1, 8): 'Van Vleck'}
%% Cell type:markdown id: tags:
### 21.3 Use namedtuple (immutable) to store user-defined data objects.
- namedtuple is useful for creating well-defined objects
- namedtuple is like a mix of tuples and dictionaries
- let's look at the slides
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# A namedtuple is like its own kind of type!
# its a Python convention to use a Capital letter when naming a namedtuple
# define a namedtuple called Person
Person = namedtuple("Person", ["fname", "lname", "age"])
# make a single person....pls don't name it person !!
p1 = Person("Stevie", "Kuemmel", 14)
print(p1)
```
%% Output
Person(fname='Stevie', lname='Kuemmel', age=14)
14
%% Cell type:code id: tags:
``` python
# print out just their age using the 'dot' notation
print(p1.age)
```
%% Cell type:code id: tags:
``` python
# Create another Person ...this time use keyword arguments
person2 = None
```
%% Cell type:code id: tags:
``` python
# make a list of Person
people=[
Person("Alice", "Anderson", 30), # positional arguments
Person("Bob", "Baker", 31),
# add two more Persons to people,
]
```
%% Cell type:code id: tags:
``` python
# say 'Hello Alice'
```
%% Cell type:code id: tags:
``` python
# add p2 to your people list
print(people)
```
%% Cell type:code id: tags:
``` python
# say hello to each person in the list by using their first name
```
%% Cell type:code id: tags:
``` python
# make a list of just the first names
```
%% Cell type:code id: tags:
``` python
# write a function to find the average age of the Persons in people
# Practice
def avg_age(p_list):
# assume p_list is a list of Person
sum = 0
return sum
avg_age(people)
```
%% Cell type:markdown id: tags:
### Namedtuples have a deeper significance....the namedtuples we create are their own type
%% Cell type:markdown id: tags:
![namedtuple.png](attachment:namedtuple.png)
%% Cell type:code id: tags:
``` python
# how can you demonstrate that namedtuples are immutable
# but lists of namedtuples are mutable
```
%% Output
15
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
%% Cell type:code id: tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment