Chap 7 Lists and Tuples
Megan owns a small neighborhood coffee shop, and she has six employees who work as baristas (coffee bartenders). All of the employees have the same hourly pay rate. Megan has asked you to design a program that will allow her to enter the number of hours worked by each employee, then display the amounts of all the employees' gross pay. You determine the program should perform the following steps: For each employee: get the number of hours worked and store it in a list element. For each list element: use the value stored in the element to calculate an employee's gross pay. Display the amount of the gross pay.
# NUM_EMPLOYEES is used as a constant for the size of the list. NUM_EMPLOYEES = 6 def main(): --#Create a list to hold employee hours. --hours = [0] * NUM_EMPLOYEES --#Get each employee's hours worked. --for index in hours: ---print('Enter the hours worked by employee ', index + 1, ':', sept='', end='') ---hours[index] = float(input()) --# Get the hourly pay_rate = float(input('Enter the hourly pay rate: ')) --#Display each employee's gross pay. --for index in range(NUM_EMPLOYEES): ---gross_pay = hours[index] * pay_rate ---print('Gross pay for the employee ', index + 1, ':$', format(gross_pay, ',.2f'), sep=' ') # Call the main function. main()
in Operator Example
# This program demonstrates the in operator # used with a list def main(): # create a list of product numbers. prod_nums = ['V475' ,'F987', 'Q143', 'R688'] # get a product number to search for search = input("Enter a product number: ") # Determine whether the product name is in the list. if search in prod_nums: print(search, "was found in the list") else: print(search, "was not found in the list") # call the main function main()
Program gets sales amounts from the user and assigns them to a list
# the NUM_DAYS constant holds the number of days that we will gather sales data for NUM_DAYS = 5 def main(): # create the list to hold the sales for each day sales = [0]* NUM_DAYS # create a variable to hold an index index = 0 print("Enter the sales for each day.") # Get the sales for each day. while index < NUM_DAYS: print("Day #" , index + 1, ": ", sep='', end='') sales[index]= float(input()) index += 1 # Display the value entered print("Here are the values you entered: ") for value in sales: print(value) # call the main function main()
Invalid indexes do not cause slicing expressions to raise an exception.
- If the end index specifies a position beyond the end of the list, python will use the length of the list instead. - If the start index specifies a position before the beginning of the list, python will use 0 instead. - If the start index is greater than the end index, the slicing expression will return an empty list.
The append Method
- add items to the end of a list. - the item that is passed as an argument is appended to the end of the list's existing elements.
The insert Method
- allows to insert an item into a list at a specific position. - 2 arguments: an index specifying where the item should be inserted, and the item that you want to insert.
List
- contains multiple data items - contents can be changed during a program's execution - dynamic data structures (items may be added to or removed from them)
The min and max Functions
- min function accepts a sequence and returns the item that has the lowest value in the sequence. min(my_list) - max function accepts a sequence and returns the item that has the highest value in the sequence. max(my_list)
The sort Method
- rearranges the elements of a list in ascending order(lowest to highest)
del Statement
- remove an item from a specific index. del my_list[2]
The remove method
- removes an item from a list. - ValueError exception is raised if the item is not found in the list.
The index Method
- returns the index of the first element whose value is equal to item. - ValueError exception raised if item is not found in the list.
The reverse Method
-simply reverses the order of the items in the list. my_list.reverse()
List Slicing Example numbers = [1,2,3,4,5] 1. print(numbers[1:3]) 2. print(numbers[:3]) # 0 as the starting index 3. print(numbers[2:]) # use length of the list as the end index 4. print(numbers[:]) # a copy of entire list 5. print(numbers[1:4:2] #step value 6. print(numbers[-4:])
1. [2,3] 2. [1,2,3] 3. [3,4,5] 4. [1,2,3,4,5] 5. [2,4] 6. [2,3,4,5]
Element
Each item is stored in a list
Indexing
First element is 0, second is 1. Last is -1, next to last is -2. last is 1 less than the number elements in the list. Last number Indexing = len(list) - 1
two-dimensional Lists (nested list)
Is a list that has other lists as it element. Students= [['joe', 'kim'], ['sam', 'sue'], ['kelly', 'chris']]. Students[0] = ['joe', 'kim']
Sequence
Is an object that holds multiple items of data, stored one after the other
Concatenating Lists (+) (+=)
Join 2 things together. list1 = [1,2,3,4] list2 =[5,6,7,8] list3= list1 + list2 Or list1+= list2 [1,2,3,4,5,6,7,8]
Difference between lists and tuples
List is mutable (a program can change its contents) Tuple is immutable ( once it is created, its contents cannot be changed)
Copying Lists Ways list1 and list2 will reference two separate but identical lists.
Way 1: list1 =[1,2,3,4] list2 =[] for item in list1: --list2.append(item) Way 2: list1 = [1,2,3,4] list2 = [] + list1
numbers = [0] * 5
[0,0,0,0,0]
numbers = list(range(5))
[0,1,2,3,4]
numbers = [1,2,3] * 3
[1,2,3,1,2,3,1,2,3]
numbers = list(range(1, 10, 2))
[1,3,5,7,9]
List Slicing list_name[start:end] start up to (but not including) end
a slicing expression selects a range of elements from a sequence
List Methods
append(item) index(item) insert(index, item) sort() remove(item) reverse()
Passing a list as an argument to a function
def greet_users(names): """Print a simple greeting to everyone.""" for name in names: msg = "Hello, " + name + "!" print(msg) usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)
Example append Method
def main(): # Create an empty list --name_list = [] # Create a variable to control the loop. --again = 'y' # Add some names to the list. while again == 'y': ---# Get a name from the user. ---name = input('Enter a name: ') ---#Append the name to the list. ---name_list.append(name) ---# Add another one ---print('Do you want to add another name?') ---again = input('y = yes, anything else = no: ') ---print() --# Display the names that were entered. --print('Here are the name you entered.') --for name in name_list: ---print(name) # Call the main function main()
Example index Method
def main(): --# Create a list with some items. --food = ['Pizza', 'Burgers', 'Chip'] --#Display the list. --print('Here are the items in the food list:') --print(food) --#Got the item to change --item = input(Which item should I change ) --try: ---# Get the item's index in the lists. ---item_index = food.index(item) ---# Get the value to replace it with. ---new_item = input("Enter the new value: ') ---# Replace the old item with the new item. ---food[item_index] = new_item ---# Display the list. ---print('Here is the revised list:') ---print(food) --except ValueError: ---print('That item was not found in the list.') # Call the main function main()
Example insert Method
def main(): --# Create a list with some names. --names = ['James', 'Kathryn', 'Bill'] --#Display the list. --print('The list before the insert') --print(names) --#Insert a new name at element 0. --names.insert(0, 'Joe') --#Display the list again. --print('The list after the insert:') --print(names) #Call the main function main()
Totaling values in a list
def main(): --# Create a list. --numbers = [2,4,6,8,10] --# Create a variable to use as an accumulator. --total = 0 --# Calculate the total of the list elements. --for value in numbers: ---total += value --# Display the total of the list elements. --print('The total of the elements is', total) # Call the main function. main()
Passing a list as an argument to a function
def main(): --# Create a list. --numbers = [2,4,6,8,10] --# Display the total of the list elements. --print('The total is', get_total(numbers)) # The get_total function accepts a list as an argument returns the total of the values in the list. def get_total(value_list): --# Create a variable to use as an accumulator. --total = 0 --#Calculate the total of the list elements. --for num in value_list: ---total += num --#Return the total. --return total # Call the main function main()
Averaging the Values in a List
def main(): --# Create a list. --scores = [2.5, 7.3, 6.5, 4.0, 5.2] --#Create a variable to use as an accumulator. --total= 0.0 --# Calculate the total of the list elements. --for value in scores: ---total += value --# Calculate the average of the elements. --average = total / len(scores) --# Display the total of the list elements. --print('The average of the elements is ', average) # Call the main function main()
Example remove Method
def main(): --food = ['Pizza', 'Burgers', 'Chips'] --print('Here are the items in the food list:') --print(food) --item = input('Which item should I remove?') --try: ---food.remove(item) ---print('Here is the revised list: ') ---print(food) --except ValueError: ---print('That item was not found in the list.') main(()
Finding items in lists with the in operator
item in list. or not in return true if item is found in the list, or false otherwise.
Use len function to prevent an IndexError exception
my_list = [10,20,30,40] index = 0 while index < len(my_list): print(my_list[index]) index += 1
Len function
my_list = [10,20,30,40] size = len(my_list) 4
Iterating over a list with the for loop
numbers = [99,100,101,102] for n in numbers: print(n) 99 100 101 102
Copying Lists
to make a copy of a list, you must copy the list's elements.