59
Lists CSCI 1101B

CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists

CSCI 1101B

Page 2: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Warm-up Exercise

def order(food): food = food.upper() print(“Could I have a big ” + food + “ please?”) return “fresh ” + food

food = order(“pasta”)

After this program runs…1. What is the global value of food?2. What is printed out to the screen?

Page 3: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Warm-up Exercise

def order(food): food = food.upper() print(“Could I have a big ” + food + “ please?”) return “fresh ” + food

food = order(“pasta”)

After this program runs…1. Global value of food == “fresh PASTA”2. Printed: Could I have a big PASTA please?

Page 4: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Today’s Outline

● Lists: Definition, Built-in Functions

● Strings and Lists: Similarities

● Splitting Strings

● Mutable vs. Immutable, List Methods

● Iteration (Brief Intro)

Page 6: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Storing ingredients as values

ingredient_1 = “bread”

ingredient_2 = “cheese”

ingredient_3 = “butter”

Page 7: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Credit: EncycloPetey

Page 8: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Storing ingredients as values

ingredient_1 = “bread”

ingredient_2 = “cheese”

ingredient_3 = “ham”

ingredient_4 = “lettuce”

ingredient_5 = “chicken salad”

ingredient_6 = “tomato”

...

Page 9: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Part I

Lists

Page 10: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists

The general form of a list is:

[<<expression_1>>, <<expression_2>>, …, <<expression_n>>]

Page 11: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists

The general form of a list is:

[<<expression_1>>, <<expression_2>>, …, <<expression_n>>]

Examples:

ingredients = [“bread”, “cheese”, “ham”]

Page 12: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists

The general form of a list is:

[<<expression_1>>, <<expression_2>>, …, <<expression_n>>]

Examples:

ingredients = [“bread”, “cheese”, “ham”]

test_scores = [97, 88, 95]

Page 13: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

More Examples!

Credit: Gary Peeples/USFWS; Sue

Cameron

Page 14: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists can contain different data types

The “Cocoa Frog”

Credit: Stuart V Nielsen

Page 15: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists can contain different data types

cocoa_frog = [“male”, 2.5, “resting”]

Page 16: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Nesting Lists

cocoa_frog = [“male”, [2.5, “inches”], “resting”]

Page 17: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

List of Lists: Example 1

new_species = [

[“cocoa frog”, 3],

[“crayola katydid”, 6],

[“pac-man frog”, 1],

[“lilliputian beetle”, 4]

]

Page 18: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

List of Lists: Example 2

ingredients = [

[3.5, “cup”, “flour”],

[4, “teaspoon”, “baking powder”],

[5, “tablespoon”, “butter”],

[4, “tablespoon”, “sugar”]

]

Page 19: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists: Built-in Functions

len([“a”, “b”, “c”]) => 3

Page 20: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists: Built-in Functions

len([“a”, “b”, “c”]) => 3

max([84, -2, 32]) => 84min([84, -2, 32]) => -2

Page 21: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists: Built-in Functions

len([“a”, “b”, “c”]) => 3

max([84, -2, 32]) => 84min([84, -2, 32]) => -2

sum([1, 2, 0]) => 3

Page 22: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists: Built-in Functions

len([“a”, “b”, “c”]) => 3

max([84, -2, 32]) => 84min([84, -2, 32]) => -2

sum([1, 2, 0]) => 3

sorted([1, 2, 0]) => [0, 1, 2]

Page 23: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Part II

Strings and Lists:Similarities

Page 24: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

● We can find the length of a list or a string with len()

len([1, 3, 4, 4, 7]) => 5

len(“some words”) => 10

Page 25: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

The Empty List

A list with nothing in it is called an empty list.

no_elements = []

A string with no characters is called an empty string.

no_characters = “”

Page 26: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

The Empty List

We can use conditionals to check if strings or lists are empty.

if 0: print(“This won’t ever print.”)

if “”: print(“Neither will this.”)

if []: print(“Oh, and this won’t, either.”)

Page 27: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

● We can count the number of occurrences of an element in a list (just like we can count substrings)

[1, 3, 4, 4, 7].count(4) => 2

● We can find the index of the first occurrence of an element (again, just like substrings)

[1, 3, 4, 4, 7].index(4) => 2

Page 28: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

● We can concatenate lists with the + operator

[1, 2] + [3] => [1, 2, 3]

● We can also multiply a list by an int (not as common):

[1, 2] * 3 = [1, 2, 1, 2, 1, 2]

Page 29: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

We can use the “in” operator with lists!

fruits = [“apple”, “lemon”, “kiwi”]

user_fruit = input(“Enter a fruit: ”)

if user_fruit.lower() in fruits:

print(“Oh! I know that one!”)

Page 30: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

We can also slice lists, just like strings!

ingredients = [“bread”, “cheese”, “tomato”]

ingredients[0] => ‘bread’ingredients[-1] => ‘tomato’ingredients[:2] => ['bread', 'cheese']ingredients[:] => ['bread', 'cheese', ‘tomato’]

0 1 2

Page 31: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Differences?

my_list = [1, 2, 3]

my_list[0] = 7

=> Now, my_list is [7, 2, 3]

Page 32: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings and Lists: Similarities

my_list = [1, 2, 3]

my_list[0] = 7

=> Now, my_list is [7, 2, 3]

my_string = “hello”

my_string[0] = “y”

=> This results in a TypeError

Page 33: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Part III

Mutable vs. Immutable

Page 34: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings are Immutable

x = “one”y = xz = y

Page 35: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings are Immutable

x = “one”y = xz = yz += “two”

Page 36: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Strings are Immutable

x = “one”y = xz = yz += “two”

What are the values assigned to x, y, and z?

x == y == “one”z == “onetwo”

Page 37: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists are Mutable

x = [1, 2, 3]y = xz = y

Page 38: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists are Mutable

x = [1, 2, 3]y = xz = yz += [4]

Page 39: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists are Mutable

x = [1, 2, 3]y = xz = yz += [4]

What are the values assigned to x, y, and z?

x == y == z == [1, 2, 3, 4]

Page 40: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Lists are Mutable

If you want to copy a list (so that the original list doesn’t mutate), use slicing notation:

x = [1, 2, 3]y = x[:]y += [8]

Now x = [1, 2, 3] and y = [1, 2, 3, 8]

Page 41: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

More List Methods

insert(index, object): inserts object into list before index

pop(index): remove and return object at index (defaults to last if no argument given)

remove(value): removes first occurrence of value

reverse(): reverses the contents of the list

sort(): like built-in sorted function

Be careful - all of these except for pop() return None

Page 42: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Assigning to a non-existent index

my_list = [“apple”, “lemon”, “kiwi”]

Page 43: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Assigning to a non-existent index

my_list = [“apple”, “lemon”, “kiwi”]

my_list[0] = “strawberry”

Page 44: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Assigning to a non-existent index

my_list = [“apple”, “lemon”, “kiwi”]

my_list[0] = “strawberry”

my_list[6] = “blueberry”

Page 45: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Assigning to a non-existent index

my_list = [“apple”, “lemon”, “kiwi”]

my_list[0] = “strawberry”

my_list[6] = “blueberry”

This will cause an IndexError - we are trying to access an index that is out of the range of indices available.

Page 46: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

append() is different from extend() (or +)

● append() adds exactly one element

my_list = [1, 2, 3]my_list.append(4) # => my_list = [1, 2, 3, 4]

Page 47: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

append() is different from extend() (or +)

● append() adds exactly one element

my_list = [1, 2, 3]my_list.append(4) # => my_list = [1, 2, 3, 4]

● extend() (or +) will merge two lists

my_list = [1, 2, 3]my_list.extend([4, 5]) # => my_list = [1, 2, 3, 4, 5]

Page 48: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

split() and join()

We can make strings into lists:

sent = “once upon a time” sent.split(“ ”) => [“once”, “upon”, “a”, “time”]

...and lists into strings:

words = [“once”, “upon”, “a”, “time”] “ ”.join(words) => “once upon a time”

Page 49: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Question

What if we wanted to perform an operation on every element of a list (or every character of a string)?

● Example: multiply each number in a list by three.

multiply_by_three([1, 2, 3, 4]) => [3, 6, 9, 12]

Page 50: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Part IV

Iteration

Page 51: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Another way to use the “in” operator

for <<variable>> in <<list>>:

<<block>>

Loops let us repeat code!

Here is the general form for a “for each” loop over a list:

Page 52: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Example: Singing a Song Really Loudly

Credit:sunnyskyz.com

Page 53: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

For Each Loops help us repeat code

phrases = [“the real life”, “just fantasy”]

Page 54: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

For Each Loops help us repeat code

phrases = [“the real life”, “just fantasy”]

for phrase in phrases:

Page 55: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

For Each Loops help us repeat code

phrases = [“the real life”, “just fantasy”]

for phrase in phrases: print(“IS THIS ” + phrase.upper() + “?”)

Page 56: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

For Each Loops help us repeat code

phrases = [“the real life”, “just fantasy”]

for phrase in phrases: print(“IS THIS ” + phrase.upper() + “?”)

IS THIS THE REAL LIFE?IS THIS JUST FANTASY?

Page 57: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

For Each Loop - Examples

Strings:

for character in “a little string”: print(character)

Lists:

for element in [1, 4, 7, 11]: print(element * element)

Page 58: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Summary (1)

● Lists are one way to store collections.

● We can use the “in” operator to not only determine whether elements of a list exist, but to iterate through a list (or string) using a for each loop.

● Lists have a lot in common with strings. However, there are some key differences. For example...

Page 59: CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints, floats, and bools) are immutable. We can’t change individual elements. All we can

Summary (2)

● Lists are mutable: ○ We can change elements without creating an entirely new object.○ Applying methods, like pop(), will change the list object.○ To keep a list from changing, use a copy (or assign a value).

● Strings (and ints, floats, and bools) are immutable. ○ We can’t change individual elements. All we can do is assign a

new value to the same name.○ Applying methods will not change the original object without a

reassignment statement.