0% found this document useful (0 votes)
11 views16 pages

C2047 Ch06 Lecture Pizza

Chapter 6 covers lists and tuples in Python, explaining their characteristics, methods, and built-in functions. It provides a practical example of creating a pizza ordering program that allows users to add and remove toppings from a list. The chapter emphasizes the differences between mutable and immutable types, showcasing various list operations and their effects.

Uploaded by

hudson.jake824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

C2047 Ch06 Lecture Pizza

Chapter 6 covers lists and tuples in Python, explaining their characteristics, methods, and built-in functions. It provides a practical example of creating a pizza ordering program that allows users to add and remove toppings from a list. The chapter emphasizes the differences between mutable and immutable types, showcasing various list operations and their effects.

Uploaded by

hudson.jake824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

COP 2047 Chapter 6 – Lists and Tuples Page 1 of 16

Step 1 – Introduction – Chapter 6 – Lists and Tuples


• There are three basic sequence types: lists, tuples, and range objects
• list – collection of items
o A list is like an array in other programming languages and each item is like an element
o index – used to refer to an item in a list
▪ The first item is at index 0
▪ The second item is at index 1
▪ And so, on
o Items can also be indexed in a negative fashion
▪ The last item is at index -1
▪ The next to last item is at index -2
▪ And so, on
▪ This is an unusual feature
o Python provides many methods for lists:
▪ append(item) – append specified item to the end of the list
▪ insert(index, item) – insert specified item at the index (rest of items will be shifted down)
▪ remove(item) – remove first matching item from the list (item must be in the list)
▪ index(item) – returns the index of first matching item from the list (item must be in the list)
▪ pop([index]) – removes the last item in the list, or item at specified index
▪ count(item) – returns the number of times item occurs in the list
▪ reverse() – reverses the items in the list
▪ sort([key=function]) – sorts the list with optional function to be called for each item before
sorting
o Python has built-in functions for lists
▪ len(list) – returns the length of the list (the number of items)
▪ sorted(list [, key=function]) – returns a new sorted list with optional function to be called for
each item before sorting
▪ min(list) – returns the minimum value in the list
▪ max(list) – returns the maximum value in the list
▪ choice(list) – returns a randomly selected item in the list (in the random module)
▪ shuffle(list) – shuffles the items in the list (in the random module)
▪ deepcopy(list) – returns a deep copy (a new list with no relation to the original list) (in the copy
module)
• tuple – a data structure that can contain multiple items (like a list), but tuples are immutable
o immutable – cannot be modified

Step 2 – Start pizza.py with a list of toppings


• Write a Python program that will help the customer build a pizza
o Add additional topping choices
o Present menu of toppings
o Let the user add toppings
o Choose size of pizza
o Print the order
• Create a list of toppings
o The items in a list are enclosed in square brackets
▪ Place a comma and a space between each item
o A list can be created in a variety of ways. To create an empty list:
COP 2047 Chapter 6 – Lists and Tuples Page 2 of 16

toppings = []

o A list can be created with items in the list


▪ This is the one we are going to use. It will add two items to the list
toppings = ['extra cheese', 'pepperoni', 'mushrooms']

o A list can be created with multiple copies of the same item


▪ The repetition operator, *, is used to repeat items in a list
▪ The following would create a list with 3 items, all of them ‘cheese’
toppings = ['cheese'] * 3

• There are a variety of ways to access items and print them


o Print the entire list. Note this will look very much like the assignment statement
print(toppings)

o Access and print a single item from the list. [0] is the first item, [-1] is the last item
print(toppings[0])
print(toppings[-1])

o Use a for loop to iterate over each item in the list


▪ Note that changing the value of top will not change the value in the list.
• Can use for i in range(len(toppings)) so toppings[i] can be referenced inside the for loop
• This will allow items to be modified in a for loop
for top in toppings:
print(top)

• pizza.py:
#!/usr/bin/env python3

def main():
toppings = ['extra cheese', 'pepperoni', 'mushrooms']

print('The entire list:')


print(toppings)

print('\nThe first item:')


print(toppings[0])

print('\nThe last item:')


print(toppings[-1])

print('\nThe list, one item at a time:')


for top in toppings:
print(top)

if __name__ == '__main__':
COP 2047 Chapter 6 – Lists and Tuples Page 3 of 16

main()

• Run the program:


The entire list:
['extra cheese', 'pepperoni', 'mushrooms']

The first item:


extra cheese

The last item:


mushrooms

The list, one item at a time:


extra cheese
pepperoni
mushrooms

Step 3 – Modify the list by adding more toppings


• Take advantage of the Python shell to several addition list functions and methods
o Remember in the shell, you can type a variable name, function call, and/or expression and the
result/value is printed
• There are many list methods – here are a few:
o The append method can be used to add an item to the end of the list
▪ Note + and += operators can be used to concatenate lists together
▪ A list method is called by coding the list name, a dot, and the method to be called
>>> toppings = ['extra cheese', 'pepperoni', 'mushrooms']
>>> toppings.append('sausage')
>>> toppings
['extra cheese', 'pepperoni', 'mushrooms', 'sausage']

o The insert method can be used to insert an item at a particular location in the list
>>> toppings.insert(1, 'onions')
>>> toppings
['extra cheese', 'onions', 'pepperoni', 'mushrooms', 'sausage']

o The pop method removes the last item in the list


>>> toppings.pop()
'sausage'
>>> toppings
['extra cheese', 'onions', 'pepperoni', 'mushrooms']

o The pop method has an optional parameter that indicates which item to remove from the list
>>> toppings.pop(1)
'onions'
>>> toppings
['extra cheese', 'pepperoni', 'mushrooms']

o The count method returns the number of times an item appears in the list
▪ If the item does not exist in the list, an exception is thrown
COP 2047 Chapter 6 – Lists and Tuples Page 4 of 16

>>> toppings.count('mushrooms')
1

• Modify pizza.py to let the user add toppings to the list


o Start by removing all of main’s code except for the first line of main
toppings = ['extra cheese', 'pepperoni', 'mushrooms']

o Prompt the user to add extra toppings to the list of choices


▪ The way this loop is structure, ‘exit’ will get added to end of the list which is why there is a call
to pop after the loop
▪ There are other ways to design the loop that would eliminate the call to pop, but it allows us to
demonstrate both append and pop in our final pizza program
def main():
toppings = ['extra cheese', 'pepperoni', 'mushrooms']
topping = 'not exit'

while topping != 'exit':


topping = input('Topping? ')
print()
toppings.append(topping.lower())
toppings.pop()
print(toppings)

• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple

Topping? bacon

Topping? exit

['extra cheese', 'pepperoni', 'mushrooms', 'pineapple', 'bacon']

Step 4 – Modify the list by removing a topping


• The remove method is used to remove an item from a list
o Note that the item must be in the list, otherwise an exception will be thrown
• The in operator is used to check if a value exists in a sequence or not
if to_remove.lower() in tops:

• Write a function modifies the list by removing an item if it is present


o I purposely called lower and upper in multiple places to help clarify mutable and immutable objects
(which is explained below)
def remove_topping(tops, to_remove):
if to_remove.lower() in tops:
tops.remove(to_remove.lower())
to_remove = to_remove.upper()
print('Removed: ' + to_remove)
else:
print('Sorry that topping is not in the list')
COP 2047 Chapter 6 – Lists and Tuples Page 5 of 16

• Modify pizza.py to prompt the user and call the new remove_topping function
o Add the following lines to the end of main
topping = input('Topping to remove from menu? ')
print()
remove_topping(toppings, topping)
print(toppings)

• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple

Topping? bacon

Topping? exit

['extra cheese', 'pepperoni', 'mushrooms', 'pineapple', 'bacon']


Topping to remove from menu? Pepperoni

Removed: PEPPERONI
['extra cheese', 'mushrooms', 'pineapple', 'bacon']

• Objects – how Python stores data of all types including integers, strings, floating point numbers, and lists
o immutable type – data cannot be changed but a new object can be created
▪ str, int, float, and bool are immutable types
o mutable type – data can be changed
▪ list is a mutable type
• Trace through the new lines to understand how mutable and immutable types work
o Execute the line: topping = input('Topping to remove from menu? ') when the user
has typed Pepperoni
▪ The following is a graphical version of what has happened
▪ Do not forget that we had earlier made the toppings list and it has 5 items

o Now, call the remove_topping function


▪ to_remove will reference the same PyObject at topping
COP 2047 Chapter 6 – Lists and Tuples Page 6 of 16

▪ tops will reference the same PyObject as toppings


▪ Neither topping nor toppings will be visible while we are in the remove_topping function

o The if Boolean expression was True, go into the If statement


o Execute tops.remove
▪ lists are mutable – modify the list
▪ Notice how tops in remove_topping and toppings in main both reference the same object
▪ When tops is changed (pepperoni, the second item is removed), toppings is also changed
▪ The string object with ‘pepperoni’ has been abandoned. No one is referencing that object
anymore

o Execute to_remove = to_remove.upper()


▪ Strings are immutable. When the value is changed, a new object is created
▪ Notice how to_remove is ‘PEPPERONI’, but topping (from main) is still ‘Pepperoni’
▪ When passing immutable types to functions, any changes that the function makes to those
variables will not affect the variables from the caller
COP 2047 Chapter 6 – Lists and Tuples Page 7 of 16

o Execute print('Removed: ' + to_remove)


▪ This will print: Removed: PEPPERONI
o The function ends and control is passed back to main
▪ to_remove and tops go out of scope
• Now, both pepperoni and PEPPERONI have been abandoned
▪ topping and toppings come back into scope

• Do not worry about all these ‘abandoned’ objects


o Python has garbage collection that will clean up abandoned objects

Step 5 – Sort and shuffle the list (plus other built-in functions and list methods)
• Take advantage of the Python shell to several addition list functions and methods
o Remember in the shell, you can type a variable name, function call, and/or expression and the
result/value is printed
• There are many built-in functions and list methods – here are a several more:
COP 2047 Chapter 6 – Lists and Tuples Page 8 of 16

o slicing gets a subset of a list


▪ name_of_list[start:stop:step]
▪ start defaults to 0
▪ stop is one past the last index to be sliced
>>> fruit = ['apple', 'ORANGE', 'banana', 'grape']
>>> fruit[0:2]
['apple', 'ORANGE']
>>> fruit[:2]
['apple', 'ORANGE']
>>> fruit[2:]
['banana', 'grape']
>>> fruit[0:4:2]
['apple', 'banana']

o len(list) function returns the number of items in the list


>>> len(fruit)
4

o reverse() method reverses the items in the list


>>> fruit.reverse()
>>> fruit
['grape', 'banana', 'ORANGE', 'apple']

o sort([key=function]) method sorts the items in the list


▪ If the key parameter is used, then the function will be applied to each item before sorting
▪ The first call to sort ORANGE was placed first because uppercase letters are before lowercase
▪ If you are sorting strings, be sensitive to the case of the letters.
• You can pass in key=str.lower to change all strings to lowercase before sorting
• Pay close attention to how the list keeps its original item values even with the key,
ORANGE is in the list even though it used orange during the sort
>>> fruit.sort()
>>> fruit
['ORANGE', 'apple', 'banana', 'grape']
>>> fruit.sort(key=str.lower)
>>> fruit
['apple', 'banana', 'grape', 'ORANGE']

o sorted(list[, key=function]) function works like sort except a new list is created and returned
▪ Reset the list to demonstrate sorted
▪ fruit keeps its items in the original order, fruit_2 is a second list where the items are sorted
>>> fruit = ['apple', 'ORANGE', 'banana', 'grape']
>>> fruit_2 = sorted(fruit)
>>> fruit
['apple', 'ORANGE', 'banana', 'grape']
>>> fruit_2
['ORANGE', 'apple', 'banana', 'grape']

o min(list) function returns the smallest item in the list


▪ Remember uppercase letters are before lowercase letters
COP 2047 Chapter 6 – Lists and Tuples Page 9 of 16

>>> min(fruit)
'ORANGE'

o max(list) function returns the largest item in the list


>>> max(fruit)
'grape'

o choice(list) function returns a random item in the list


▪ Must import random
>>> import random
>>> random.choice(fruit)
'ORANGE'
>>> random.choice(fruit)
'apple'
>>> random.choice(fruit)
'grape'

o shuffle(list) function randomly shuffles the items in the list


▪ Must import random
>>> random.shuffle(fruit)
>>> fruit
['apple', 'ORANGE', 'banana', 'grape']

o deepcopy(list) function creates and returns a new copy of the list


▪ Must import copy
▪ fruit_shallow is a shallow copy – both fruit and fruit_shallow reference the same list object
• When the fruit_shallow list is changed, so is fruit because they point both to the same
object
▪ fruit_deep is a deep copy of fruit – it is a completely separate list
• When the fruit_deep list is changed, fruit is not changed
>>> fruit_shallow = fruit
>>> fruit_shallow[1] = 'pear'
>>> fruit_shallow
['apple', 'pear', 'banana', 'grape']
>>> fruit
['apple', 'pear', 'banana', 'grape']
>>> import copy
>>> fruit_deep = copy.deepcopy(fruit)
>>> fruit_deep[1] = 'peach'
>>> fruit_deep
['apple', 'peach', 'banana', 'grape']
>>> fruit
['apple', 'pear', 'banana', 'grape']

• Write a function to change how the topping list is presented to the user
def organize_toppings(tops):
organize = input('s(h)uffle, (r)everse, (s)ort, (n)one? ')
if organize.upper() == 'H':
random.shuffle(tops)
elif organize.upper() == 'R':
COP 2047 Chapter 6 – Lists and Tuples Page 10 of 16

tops.reverse()
elif organize.upper() == 'S':
tops.sort(key=str.lower)

• Modify pizza.py to call the new organize_toppings function


o Add the following line to the end of main
organize_toppings(toppings)
print(toppings)

• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple

Topping? bacon

Topping? exit

['extra cheese', 'pepperoni', 'mushrooms', 'pineapple', 'bacon']


Topping to remove from menu? Pepperoni

Removed: PEPPERONI
['extra cheese', 'mushrooms', 'pineapple', 'bacon']
s(h)uffle, (r)everse, (s)ort, (n)one? r
['bacon', 'pineapple', 'mushrooms', 'extra cheese']

Step 6 – Add list of lists to build the order


• A list of lists is like a two-dimensional array that you may have seen in other languages
o Two-dimensional list – another name for list of lists
▪ Can view the data as columns within each row
o Create an empty list
order = []

o Create a list for the first ‘row’ of order


▪ Not all items in a list must be the same data type
• Following the
▪ Our list has a string and an integer
one_topping = ['bacon', 1]

o Append the first ‘row’ to the order list


order.append(one_topping)

o A list of lists can be created in a single line too


order = [['bacon', 1], ['extra cheese', 1], ['mushrooms', 0],
['pineapple', 2]]

o To access a single item, use two sets of [ ]’s – the first for topping list, and the second for the item within
the topping list
order[0][1] += 1 # Adds 1 to extra’s cheese count
COP 2047 Chapter 6 – Lists and Tuples Page 11 of 16

• The index method returns the index of the item passed in


o Note that the item must be in the list, otherwise an exception will be thrown
o Gets the index (0 to number of items – 1) of topping in the tops list
tops.index(topping)

• Write a function creates the order list and prompts the user for toppings until exit is entered
def order_toppings(tops, order):
# Create a list of lists, each row is a topping with 0 count
for top in tops:
one_topping = []
one_topping.append(top)
one_topping.append(0)
order.append(one_topping)

# Prompt user, adding 1 to count of matching topping


topping = input(str(tops) + '? ')
print()
while topping != 'exit':
order[tops.index(topping)][1] += 1
topping = input(str(tops) + '? ')
print()
order.sort() # sorts by first item in each list
print(order)

• Modify pizza.py to create an empty list and call the new remove_topping function
o Add the following lines to the end of main
order = []
order_toppings(toppings, order)

• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple

Topping? bacon

Topping? exit

['extra cheese', 'pepperoni', 'mushrooms', 'pineapple', 'bacon']


Topping to remove from menu? Pepperoni

Removed: PEPPERONI
['extra cheese', 'mushrooms', 'pineapple', 'bacon']
s(h)uffle, (r)everse, (s)ort, (n)one? r
['bacon', 'pineapple', 'mushrooms', 'extra cheese']
['bacon', 'pineapple', 'mushrooms', 'extra cheese']? bacon

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? pineapple

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? extra cheese

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? pineapple


COP 2047 Chapter 6 – Lists and Tuples Page 12 of 16

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? exit

[['bacon', 1], ['extra cheese', 1], ['mushrooms', 0], ['pineapple', 2]]

Step 7 – Add a tuple for the sizes of the pizza


• tuple - a data structure that can contain multiple items (like a list), but tuples are immutable
o This function has a single parameter, feet
o A tuple is created with ( ) instead of [ ]
sizes = ('small', 'medium', 'large', 'extra-large')

o The functions/methods for lists that did not modify the list are available for tuples. For example,
print(len(sizes)) # prints 4

o A tuple can be unpacked, which is separating the values into individual variables
▪ Unpacking is done with a multiple assignment statement
size1, size2, size3, size4 = sizes

• Modify pizza.py to create a tuple of sizes, prompt the user, and print the final order
o Add the following lines to the end of main
sizes = ('small', 'medium', 'large', 'extra-large')
size = input(('Choose a size: ' + str(sizes)) + '? ')
print('You ordered a '
+ size
+ ' pizza with '
+ str(order))

• Run the program (The bold, underlined text is what I typed when I ran the program):
o Only the new potion of the output is shown below
Choose a size: ('small', 'medium', 'large', 'extra-large')? medium
You ordered a medium pizza with [['bacon', 1], ['extra cheese', 1],
['mushrooms', 0], ['pineapple', 2]]

Step 8 –Loop over order using enumerate


• enumerate – function that adds a counter to an iteratable (such as a list or tuple)
o When combined with a for loop, can get both a counter (for example, the index) in addition to each
item
• For example, make a loop to print each item in the list with its index
o Using range and len:
▪ This works, but there are alternatives to range(len(str_list)) when wanting to access both the
index and the item from the list
str_list = ['one', 'two', 'three']
for ind in range(len(str_list)):
print(ind, str_list[ind])

o Using enumerate:
▪ Notice how print can use item instead of str_list[ind] to print the current item from the list
COP 2047 Chapter 6 – Lists and Tuples Page 13 of 16

str_list = ['one', 'two', 'three']


for ind, item in enumerate(str_list):
print(ind, item)

o Using enumerate with start value:


▪ Programmers count from 0, but most users count from 0. This version will have ind count 1, 2, 3
instead of 0, 1, 2
str_list = ['one', 'two', 'three']
for ind, item in enumerate(str_list, start=1):
print(ind, item)

• Modify pizza.py to capitalize all the toppings and print one topping per line
o Add the following lines to the end of main
o Remember that order is a list of lists. The first column is the topping name. The second column is the
count
for ind, topping in enumerate(order):
order[ind][0] = topping[0].upper()
for num, topping in enumerate(order, start=1):
print('Topping', num, 'is', topping[1], topping[0]) +

• Run the program (The bold, underlined text is what I typed when I ran the program):
o Only the new potion of the output is shown below
Topping 1 is 1 BACON
Topping 2 is 1 EXTRA CHEESE
Topping 3 is 0 MUSHROOMS
Topping 4 is 2 PINEAPPLE

Step 9 – Completed Project


• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple

Topping? bacon

Topping? exit

['extra cheese', 'pepperoni', 'mushrooms', 'pineapple', 'bacon']


Topping to remove from menu? Pepperoni

Removed: PEPPERONI
['extra cheese', 'mushrooms', 'pineapple', 'bacon']
s(h)uffle, (r)everse, (s)ort, (n)one? r
['bacon', 'pineapple', 'mushrooms', 'extra cheese']
['bacon', 'pineapple', 'mushrooms', 'extra cheese']? bacon

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? pineapple

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? extra cheese

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? pineapple


COP 2047 Chapter 6 – Lists and Tuples Page 14 of 16

['bacon', 'pineapple', 'mushrooms', 'extra cheese']? exit

[['bacon', 1], ['extra cheese', 1], ['mushrooms', 0], ['pineapple', 2]]


Choose a size: ('small', 'medium', 'large', 'extra-large')? medium
You ordered a medium pizza with [['bacon', 1], ['extra cheese', 1],
['mushrooms', 0], ['pineapple', 2]]
Topping 1 is 1 BACON
Topping 2 is 1 EXTRA CHEESE
Topping 3 is 0 MUSHROOMS
Topping 4 is 2 PINEAPPLE

• pizza.py (with comments added)


#!/usr/bin/env python3

"""Module to order a pizza."""

__author__ = 'Karen Peterson'


__date__ = '6/12/2020'

import random

def remove_topping(tops, to_remove):


"""Remove a topping from the list.

Args:
tops (list): list of toppings
to_remove (str): topping to remove

Returns:
None
"""
if to_remove.lower() in tops:
# Must know that item is in tops before calling remove
tops.remove(to_remove.lower())
to_remove = to_remove.upper()
print('Removed: ' + to_remove)
else:
print('Sorry that topping is not in the list')

def organize_toppings(tops):
"""Organize toppings in the list.

Args:
tops (list): list of toppings
to_remove (str): topping to remove

Returns:
None
"""
organize = input('s(h)uffle, (r)everse, (s)ort, (n)one? ')
if organize.upper() == 'H':
random.shuffle(tops)
COP 2047 Chapter 6 – Lists and Tuples Page 15 of 16

elif organize.upper() == 'R':


tops.reverse()
elif organize.upper() == 'S':
# sort values as lowercase, but keep original case in the list
tops.sort(key=str.lower)

def order_toppings(tops, order):


"""Add toppings to order based on user choices.

Args:
tops (list): list of toppings
order (list): list of lists of toppings and count

Returns:
None
"""
# Create a list of lists, each row is a topping with 0 count
for top in tops:
one_topping = []
one_topping.append(top)
one_topping.append(0)
order.append(one_topping)

# Prompt user, adding 1 to count of matching topping


topping = input(str(tops) + '? ')
print()
while topping != 'exit':
# Must know that item is in tops before calling index
order[tops.index(topping)][1] += 1
topping = input(str(tops) + '? ')
print()
order.sort() # sorts by first item in each list
print(order)

def main():
"""Add toppings to order based on user choices.

Args:
None

Returns:
None
"""
# lists are [ ] and are mutable
toppings = ['extra cheese', 'pepperoni', 'mushrooms']
topping = 'not exit'

while topping != 'exit':


topping = input('Topping? ')
print()
toppings.append(topping.lower())
toppings.pop()
print(toppings)
COP 2047 Chapter 6 – Lists and Tuples Page 16 of 16

topping = input('Topping to remove from menu? ')


print()
remove_topping(toppings, topping)
print(toppings)

organize_toppings(toppings)
print(toppings)

order = []
order_toppings(toppings, order)

# tuples are ( ) and are immutable


sizes = ('small', 'medium', 'large', 'extra-large')
size = input(('Choose a size: ' + str(sizes)) + '? ')
print('You ordered a '
+ size
+ ' pizza with '
+ str(order))

# capitalize and print order toppings with enumerate


for ind, topping in enumerate(order):
order[ind][0] = topping[0].upper()
for num, topping in enumerate(order, start=1):
print('Topping', num, 'is', topping[1], topping[0])

if __name__ == '__main__':
main()

You might also like