CSCI 1101B Lists - Bowdoin Collegesharmon/static/1101/lecs/1101_lec8.pdf · Strings (and ints,...

Preview:

Citation preview

Lists

CSCI 1101B

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?

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?

Today’s Outline

● Lists: Definition, Built-in Functions

● Strings and Lists: Similarities

● Splitting Strings

● Mutable vs. Immutable, List Methods

● Iteration (Brief Intro)

Storing ingredients as values

ingredient_1 = “bread”

ingredient_2 = “cheese”

ingredient_3 = “butter”

Credit: EncycloPetey

Storing ingredients as values

ingredient_1 = “bread”

ingredient_2 = “cheese”

ingredient_3 = “ham”

ingredient_4 = “lettuce”

ingredient_5 = “chicken salad”

ingredient_6 = “tomato”

...

Part I

Lists

Lists

The general form of a list is:

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

Lists

The general form of a list is:

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

Examples:

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

Lists

The general form of a list is:

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

Examples:

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

test_scores = [97, 88, 95]

More Examples!

Credit: Gary Peeples/USFWS; Sue

Cameron

Lists can contain different data types

The “Cocoa Frog”

Credit: Stuart V Nielsen

Lists can contain different data types

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

Nesting Lists

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

List of Lists: Example 1

new_species = [

[“cocoa frog”, 3],

[“crayola katydid”, 6],

[“pac-man frog”, 1],

[“lilliputian beetle”, 4]

]

List of Lists: Example 2

ingredients = [

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

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

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

[4, “tablespoon”, “sugar”]

]

Lists: Built-in Functions

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

Lists: Built-in Functions

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

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

Lists: Built-in Functions

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

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

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

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]

Part II

Strings and Lists:Similarities

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

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 = “”

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.”)

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

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]

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!”)

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

Strings and Lists: Differences?

my_list = [1, 2, 3]

my_list[0] = 7

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

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

Part III

Mutable vs. Immutable

Strings are Immutable

x = “one”y = xz = y

Strings are Immutable

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

Strings are Immutable

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

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

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

Lists are Mutable

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

Lists are Mutable

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

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]

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]

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

Assigning to a non-existent index

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

Assigning to a non-existent index

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

my_list[0] = “strawberry”

Assigning to a non-existent index

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

my_list[0] = “strawberry”

my_list[6] = “blueberry”

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.

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]

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]

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”

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]

Part IV

Iteration

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:

Example: Singing a Song Really Loudly

Credit:sunnyskyz.com

For Each Loops help us repeat code

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

For Each Loops help us repeat code

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

for phrase in phrases:

For Each Loops help us repeat code

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

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

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?

For Each Loop - Examples

Strings:

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

Lists:

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

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

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.