C2047 Ch06 Lecture Pizza
C2047 Ch06 Lecture Pizza
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])
• pizza.py:
#!/usr/bin/env python3
def main():
toppings = ['extra cheese', 'pepperoni', 'mushrooms']
if __name__ == '__main__':
COP 2047 Chapter 6 – Lists and Tuples Page 3 of 16
main()
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 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
• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple
Topping? bacon
Topping? exit
• 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
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
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 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']
>>> min(fruit)
'ORANGE'
• 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)
• Run the program (The bold, underlined text is what I typed when I ran the program):
Topping? pineapple
Topping? bacon
Topping? exit
Removed: PEPPERONI
['extra cheese', 'mushrooms', 'pineapple', 'bacon']
s(h)uffle, (r)everse, (s)ort, (n)one? r
['bacon', 'pineapple', 'mushrooms', 'extra cheese']
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
• 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)
• 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
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
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]]
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
• 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
Topping? bacon
Topping? exit
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
import random
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
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)
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'
organize_toppings(toppings)
print(toppings)
order = []
order_toppings(toppings, order)
if __name__ == '__main__':
main()