CHAPTER 7
A tuple is an immutable list, meaning that once it is defined it cannot be changed. This is different from normal lists in which you can add, remove, and change the values. With tuples none of these actions are an option. Where tuples are similar to lists is that they are ordered in the same fashion, and the values in the tuple can be still be accessed by index. In fact, you can perform many of the same operations on a tuple that you can on a list. You can concatenate tuples, you can iterate over the values in a tuple with a for loop, you can access values from the end of the tuple using negative indices, and you can access slices of a tuple. Tuples are created using comma separated values between parentheses. The pattern is tuple_name = (item_1, item_2, item_N). If you only want a single item in a tuple, that single item must always be followed by a comma. The pattern is tuple_name = (item_1,).
Tuples are key for organizing and holding data that will not, or should not change at any point during the execution of your program. Using a tuple is a great way to ensure that the values are not accidentally altered. For example, the months of the year should not change.
Code Listing 211
months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') jan = months_of_the_year[0] print(jan) print() for month in months_of_the_year: print(month) # You cannot modify values in a tuple. This will raise an exception. months_of_the_year[0] = 'New January' |
Code Listing 212
January January February March April May June July August September October November December Traceback (most recent call last): File "tuples.py", line 10, in <module> months_of_the_year[0] = 'New January' TypeError: 'tuple' object does not support item assignment |
Even though you are unable to change the values within a tuple, you can always remove the entire tuple during the execution of your program by making use of the previously mentioned del statement.
Code Listing 213
months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') print(months_of_the_year) del months_of_the_year # This will raise an exception since the tuple was deleted. print(months_of_the_year) |
Output:
Code Listing 214
('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') Traceback (most recent call last): File "tuples2.py", line 5, in <module> print(months_of_the_year) NameError: name 'months_of_the_year' is not defined |
In order to make a list from a tuple, use the list() built-in function and pass in the tuple. To create a tuple from a list, use the tuple() built-in function. The built-in function type() will display an object's type.
Code Listing 215
months_of_the_year_tuple = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') months_of_the_year_list = list(months_of_the_year_tuple) print('months_of_the_year_tuple is {}.'.format(type(months_of_the_year_tuple))) print('months_of_the_year_list is {}.'.format(type(months_of_the_year_list))) animals_list = ['toad', 'lion', 'seal'] animals_tuple = tuple(animals_list) print('animals_list is {}.'.format(type(animals_list))) print('animals_tuple is {}.'.format(type(animals_tuple))) |
Output:
Code Listing 216
months_of_the_year_tuple is <class 'tuple'>. months_of_the_year_list is <class 'list'>. animals_list is <class 'list'>. animals_tuple is <class 'tuple'>. |
If you are looking to perform a particular action on every item within a tuple, use a for loop. The pattern is for item_variable in tuple_name followed by a code block.
Code Listing 217
months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') for month in months_of_the_year: print(month) |
Output:
Code Listing 218
January February March April May June July August September October November December |
You can use tuples to assign values to multiple variables at the same time. In the following example, the variables jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, and dec are assigned the months of the year from the months_of_the_year tuple.
Code Listing 219
months_of_the_year = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec) = months_of_the_year print(jan) print(dec) |
Output:
Code Listing 220
January December |
It is also possible to use tuple assignment with lists.
Code Listing 221
contact_info = ['555-0123', '[email protected]'] (phone, email) = contact_info print(phone) print(email) |
Output:
Code Listing 222
555-0123 |
Tuple assignment can also be used with functions as well. For example, you could create a function that returns a tuple and assigns those values to different variables.
The following example uses the built-in max() and min() functions. The max() built-in function will return the largest item that is passed to it. The min() built-in function will return the smallest item that is passed to it.
Code Listing 223
def high_and_low(numbers): """Determine the highest and lowest number""" highest = max(numbers) lowest = min(numbers) return (highest, lowest) lucky_numbers = [37, 71, 47, 13, 17, 67] (highest, lowest) = high_and_low(lucky_numbers) print('The highest number is: {}'.format(highest)) print('The lowest number is: {}'.format(lowest)) |
Output:
Code Listing 224
The highest number is:71 The lowest number is: 13 |
You can also use tuple assignment in a for loop. In the following example the contacts list is comprised of a series of tuples. Each time the for loop is performed the variables name and phone will be populated with the contents of a tuple from the contacts list.
Code Listing 225
contacts = [('David', '555-0123'), ('Tom', '555-5678')] for (name, phone) in contacts: print("{}'s phone number is {}.".format(name, phone)) |
Output:
Code Listing 226
David's phone number is 555-0123. Tom's phone number is 555-5678. |
A tuple is an immutable list, which means that once it has been defined the values in the tuple cannot be changed.
The del statement can be used to delete a tuple. del tuple_name
It is possible to convert a tuple to a list using the list() built-in function.
Lists can also be converted to tuples by using the tuple() built-in function.
You can use tuple assignment to assign values to multiple variables at the same time. (var_1, var_N) = (value_1, value_N)
Tuple assignment can be used in for loops.
The max() built-in function will return the largest item that is passed to it.
The min() built-in function will return the smallest item that is passed to it.
Try creating a list of cities that will include a series of tuples that contain both a city's name and its ZIP code. Loop through the list and utilize tuple assignment. Assign one variable to denote the city name and another variable to represent the ZIP code. Display the city's name and ZIP code to the screen.
Sample output:
Code Listing 227
The ZIP code for Short Hills, NJ is 07078. The ZIP code for Fairfax Station, VA is 22039. The ZIP code for Weston, CT is 06883. The ZIP code for Great Falls, VA is 22066. |
Code Listing 228
cities = [ ('Short Hills, NJ', '07078'), ('Fairfax Station, VA', '22039'), ('Weston, CT', '06883'), ('Great Falls, VA', '22066') ] for (city, zip_code) in cities: print('The ZIP code for {} is {}.'.format(city, zip_code)) |
list() documentation: https://docs.python.org/3/library/functions.html#func-list
max() documentation: https://docs.python.org/3/library/functions.html#max
min() documentation: https://docs.python.org/3/library/functions.html#min
type() documentation: https://docs.python.org/3/library/functions.html#type
tuple() documentation: https://docs.python.org/3/library/functions.html#func-tuple