Lists - Mutability
Jake Shoudy
Sept 21, 2022
CSCI 110 - Lecture 15
Announcements
STEP Application Open
HW5
Posted last Thursday
For loops!
Due tomorrow!
Project 1: Part 4
Due Sunday 9/25 11:59PM
No new functionality!
Writing unit tests and integration tests!
Quiz 5
First 15 minutes of class on Friday
Meet in Lab
Will cover for loops and simple list operations (from Monday)
Google 20% TAs
Didn’t like your exam 1 score? Just plain lost?
Some folks from Google are volunteering their time to help you with your computer science scoolwork!
If you feel that you are falling behind and want more 1:1 attention let me know and I will try to pair you with someone who can help!
Google Mock Interviews
There is some updated availability!
Check it out: https://csci110.org/mock-interviews/#mock-interviews-with-csci110-google-tas
NO CLASS NEXT MONDAY!
Lab on Tuesday is TBD
Also no quiz next week :)
Good luck on your other midterms!
Recap
Review: Lists
What?
Data structure containing ordered list of elements, which can be strings, numbers, other data types, and other data structures including lists
Is a data type, just like str, int, bool, float
Can len(), index, slice, in, iterate
Why?
Hold data that needs to stay in a certain order
Review: Lists
dogs = ['Cooper', 'Zoey', 'Naz', 'Cocoa']
dogs[2]
len(dogs)
'Naz' in dogs
dogs[1:3]
for dog in dogs:
print(dog + ' is a good dog!')
'Naz'
4
True
['Zoey', 'Naz']
Mutability
What happens when function gets called?
def mystery(nums):
for num in nums:
print(num + 1)
What happens when function gets called?
def mystery(nums):
for num in nums:
print(num + 1)
my_list = [1, 3, 6]
mystery(my_list)
2
4
7
print(my_list)
[1, 3, 6]
Mutability
mutable: once created, value can change
immutable: once created, value cannot change
immutable types:
mutable types:
Mutability
Lists are mutable: can change elements
Strings are immutable: cannot change characters
But what about variables?
Assigning a new value to a variable is not mutating an object
x = 10
x = x + 1
x = 'Hello'
x = x[1:4]
That's just replacing value held by variable
Mutation: Change an item
friends = ['Joey', 'Rachel', 'Ross', 'Phoebe', 'Monica']
friends[1] = 'Sabrina'
friends[3] = 'James'
friends[0] = friends[2]
friends[len(friends) - 1] = 'Serena'
friends[4] = friends[3] + ' is cool'
friends[2] = 24
friends = friends[3]
['Joey', 'Sabrina', 'Ross', 'Phoebe', 'Monica']
['Ross', 'Sabrina', 'Ross', 'James', 'Monica']
['Joey', 'Sabrina', 'Ross', 'James', 'Monica']
['Ross', 'Sabrina', 'Ross', 'James', 'Serena']
['Ross', 'Sabrina', 'Ross', 'James', 'James is cool']
['Ross', 'Sabrina', 24, 'James', 'James is cool']
'James'
Mutation: Add items together
Note: This makes a new list from copies of the two given lists. It does NOT mutate either of the original arrays being concatenated.
Practice: Add items together
dogs = ['Cooper', 'Zoey']
cats = ['Magic', 'Finn']�
dogs_and_cats = dogs + cats
pets = dogs + ['Shamu', 'Salem']
['Cooper', 'Zoey', 'Magic', 'Finn']
['Cooper', 'Zoey', 'Shamu', 'Salem']
Mutation: Add an item
list.append(x)
list.insert(i, x)
Practice: Add an item
cats = []
cats.append('Magic')
cats.insert(0, 'Finn')
cats.insert(1, 'Pixie')
cats.append('Rory')
cats.insert(3, 'Tigger')
cats = []
['Magic']
['Finn', 'Magic']
['Finn', 'Pixie', 'Magic']
['Finn', 'Pixie', 'Magic', 'Rory']
['Finn', 'Pixie', 'Magic', 'Tigger', 'Rory']
Mutation: Add many items to end
y.extend(x)
Practice: Add many items to end
companies = []
companies.extend(['Google', 'Facebook'])
companies.extend(['Apple', 'Amazon', 'Zillow'])
companies.append(['Microsoft', 'Lyft'])
['Google', 'Facebook']
['Google', 'Facebook', 'Apple', 'Amazon', 'Zillow']
['Google', 'Facebook', 'Apple', 'Amazon', 'Zillow', ['Microsoft', 'Lyft']]
Mutation: Delete an item
list.pop(i)
list.remove(x)
Practice: Delete an item
classes = ['Calculus', 'CS1', 'Theology']
classes.pop(1) - What does this return? What value is classes now?
classes.remove('Theology')
classes.remove('Physics')
classes.pop()
returns 'CS1'
classes is now ['Calculus', 'Theology']
['Calculus']
ValueError
[]
Accumulator Pattern
result = []
for num in range(0, 5):
result.append(num)
print(result)
[0, 1, 2, 3, 4]
Beware!
If multiple variables refer to same list, mutating that list changes it for all variables!
your_age = 18
my_age = your_age
my_age = my_age + 1
print(your_age)
print(my_age)
states = ["WY", "SD", "MI", "LA"]
other_states = states
other_states.append("SC")
print(states)
print(other_states)
18
19
["WY", "SD", "MI", "LA", "SC"]
["WY", "SD", "MI", "LA", "SC"]
Beware!
If iterating over a list while mutating, you may have unexpected behavior
my_list = [1, 2, 3, 3, 4]
for num in my_list:
if num == 3:
my_list.remove(3)
print(my_list)
[1, 2, 3, 4]
.copy()
Instead use the .copy() function to make a copy of the list. That way we iterate over a different list than we mutate.
my_list = [1, 2, 3, 3, 4]
for num in my_list.copy():
if num == 3:
my_list.remove(3)
print(my_list)
[1, 2, 4]
Or use accumulator pattern
Alternatively we can use the accumulator pattern to avoid this issue…
my_list = [1, 2, 3, 3, 4]
result = []
for num in my_list:
if num != 3:
result.append(num)
print(result)
[1, 2, 4]
Let’s Code!
https://replit.com/team/csci110-01
Lists: Mutability
Questions?