1 of 34

Lists - Mutability

Jake Shoudy

Sept 21, 2022

CSCI 110 - Lecture 15

2 of 34

Announcements

3 of 34

STEP Application Open

Apply early! Before next week

Freshman application

Sophomore application

4 of 34

HW5

Posted last Thursday

For loops!

Due tomorrow!

5 of 34

Project 1: Part 4

Due Sunday 9/25 11:59PM

No new functionality!

Writing unit tests and integration tests!

6 of 34

Quiz 5

First 15 minutes of class on Friday

Meet in Lab

Will cover for loops and simple list operations (from Monday)

7 of 34

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!

8 of 34

Google Mock Interviews

There is some updated availability!

Check it out: https://csci110.org/mock-interviews/#mock-interviews-with-csci110-google-tas

9 of 34

NO CLASS NEXT MONDAY!

Lab on Tuesday is TBD

Also no quiz next week :)

Good luck on your other midterms!

10 of 34

Recap

11 of 34

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

12 of 34

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']

13 of 34

Mutability

14 of 34

What happens when function gets called?

def mystery(nums):

for num in nums:

print(num + 1)

15 of 34

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]

16 of 34

Mutability

mutable: once created, value can change

immutable: once created, value cannot change

immutable types:

  • int
  • float
  • bool
  • str

mutable types:

  • list
  • …?

17 of 34

Mutability

Lists are mutable: can change elements

Strings are immutable: cannot change characters

18 of 34

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

19 of 34

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'

20 of 34

Mutation: Add items together

  • operator concatenates lists 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.

21 of 34

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']

22 of 34

Mutation: Add an item

list.append(x)

  • Add element x to end of list

list.insert(i, x)

  • Insert x item at a given position i
  • First argument i is index of element before which to insert
  • a.insert(0, x) inserts at front of list
  • a.insert(len(a), x) is equivalent to a.append(x)

23 of 34

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']

24 of 34

Mutation: Add many items to end

y.extend(x)

  • x is a list
  • Add x to end of y

25 of 34

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']]

26 of 34

Mutation: Delete an item

list.pop(i)

  • i is an optional index
  • Remove item at index i from list and return it
  • If no index is provided, remove from end of list and return it
  • Returns the removed item

list.remove(x)

  • x is an item in the list
  • Remove first item from list whose value is equal to x
  • If x does not exist in list, will raise ValueError

27 of 34

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

[]

28 of 34

Accumulator Pattern

result = []

for num in range(0, 5):

result.append(num)

print(result)

[0, 1, 2, 3, 4]

29 of 34

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"]

30 of 34

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]

31 of 34

.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]

32 of 34

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]

33 of 34

Let’s Code!

34 of 34

Questions?