14. Tuples#
Tuples are sequences of values just like a list - the most significant difference is that tuples are immutable while lists are mutable. In other words, we cannot modify the sequence of values - any change creates a new tuple object.
Unlike lists, tuples are hashable, so we can use them as keys within a dictionary (to be covered in a later notebook).
Tuple indexing, slicing, and comparison perform the same as they do for lists.
To create a tuple, use a sequence of values separated by a comma. Although not necessary, the Python convention is to enclose tuples in parentheses to make the identification of tuples easier while reading code.
Also, as you can see below, both the interpreter and print()
output parenthesis when displaying tuples.
1primes = 1,2,3,5,7,11,13,17,19 # not preferred, use paranthesis
2primes
(1, 2, 3, 5, 7, 11, 13, 17, 19)
1acc_schools = ("Duke", "Notre Dame", "UNC", "NCSU", "Wake Forest", "Clemson")
2print(acc_schools)
('Duke', 'Notre Dame', 'UNC', 'NCSU', 'Wake Forest', 'Clemson')
1primes = primes + tuple([23])
2print(primes)
(1, 2, 3, 5, 7, 11, 13, 17, 19, 23)
A tuple can also be created using the built-in tuple()
function.
1four_horseman = ['Death','Destruction','Pestilence','Famine']
2tuple(four_horseman)
('Death', 'Destruction', 'Pestilence', 'Famine')
14.1. Combining Tuples +
#
Just as we use +
to concatenate strings and lists, we can also combine tuples with this operator
1('Death','Destruction','Pestilence') + ('Famine',)
('Death', 'Destruction', 'Pestilence', 'Famine')
Notice that we had to use a comma ,
with nothing after it so that the Python interpreter parses the second expression as a tuple. See what happens without the comma -
1('Death','Destruction','Pestilence') + ('Famine') #Raises a TypeError
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 1
----> 1 ('Death','Destruction','Pestilence') + ('Famine') #Raises a TypeError
TypeError: can only concatenate tuple (not "str") to tuple
As you can see, Python used the parenthesis to help determine the precedence order and considered the second expression a string.
14.2. Length#
We use the built-in function len()
to count the number of items in the tuple.
1len(primes)
10
The tuple
class has far fewer methods than the list
class - only count()
and index()
, which function similarly between the two types. Why do you think fewer methods exist for tuples?
14.3. Indexing#
1print(acc_schools[4])
2acc_schools[4] = "test"
Wake Forest
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 2
1 print(acc_schools[4])
----> 2 acc_schools[4] = "test"
TypeError: 'tuple' object does not support item assignment
14.4. Tuple assignment#
Python allows multiple assignments to variables on the left side of an assignment statement. For example, using a tuple or list on the left-hand side of the assignment operator, you can assign more than one variable at a time. We saw this example earlier with the divmod()
function that returns a tuple of the quotient and remainder.
1quotient, remainder = divmod(10,3) # paranthesis are optial for tuples.
2print("quotient={:d}, remainder={:d}".format(quotient,remainder))
quotient=3, remainder=1
Formally, this is called parallel assignment. More commonly, this is known as tuple unpacking in Python.
In addition to allowing multiple return variables from a function, a clever usage of tuple assignment is swapping the value of two variables simultaneously. Many other languages require a temporary variable.
1a = 5
2b = 7
3a, b = b, a
4print("a={:d}, b={:d}".format(a,b))
5
6# for other languages without parallel assignment
7swap = a
8a = b
9b = swap
10print("a={:d}, b={:d}".format(a,b))
a=7, b=5
a=5, b=7
Both sides of the assignment are tuples in a, b = b, a
. The Python interpreter evaluates the expressions on the right-hand side of the assignment operator from left to right. Once the interpreter evaluates those expressions, the interpreter makes the assignments to the tuple of variables on the left-hand side. The length of both tuples must be equal.
Technically, the right side can contain any sequence, even a string.
For example, we can split an email address into two parts using the ‘@’ symbol to split the string.
1email = "administrator@thedomain.com"
2(name, domain) = email.split('@')
3print("name={:s}, domain={:s}".format(name,domain))
name=administrator, domain=thedomain.com
14.5. Sequences Redux#
So far, we have seen three types of sequences - strings, lists, and tuples. In some cases, it is possible to use the types interchangeably (albeit less so with strings than lists and tuples).
So how do we choose when to use a particular sequence type?
Strings are the most limited as a sequence of characters and immutable. If you are just representing text, they are the perfect choice. However, if you need to change the characters in a string, then a list of characters might work.
Lists tend to be used more often than tuples as they are mutable.
It is generally simpler to create a tuple than a list in return statements.
If you need to use a sequence as a dictionary key, you have to use an immutable type (string, tuple)
If you pass arguments to a function, tuples can reduce the possibility of unwanted side effects as they are immutable. If the function changes the tuple (which creates a new tuple), the caller still references the original tuple when the function exits.
14.6. Suggested LLM Prompts#
Why are tuples useful in Python?
Describe a situation where using a tuple would be more appropriate than using a list.
Explain the significance of tuple packing and unpacking in Python. Provide examples of both.
Discuss common use cases for tuples in Python programming. Provide examples of situations where tuples are the preferred choice of data structure and explain the reasoning behind it.
Investigate the behavior of nested tuples in Python. How can nested tuples be used to represent hierarchical data structures, and what considerations should be taken into account when working with them?
Discuss best practices for working with tuples in Python, including naming conventions, error handling, and performance optimization techniques. How can developers effectively use tuples to enhance the readability, efficiency, and maintainability of their code?
14.7. Review Questions#
What are the differences between lists and tuples?
Explain how multiple values can be returned from a function in Python.
How are tuples created? Provide examples.
Explain how sequences work across strings, lists, and tuples.
How do you access elements in a tuple? Provide examples.
Can a tuple contain mutable objects like lists? Explain.
14.8. Exercises#
Given the following tuple assigned to the variable
data
- (‘AAPL’, 157.96, 88_140_000). Assign the items to three variables(symbol, price, and volume) and print the values.Test if the stock symbol “BAC” is in the
data
tuple.Create a new tuple of the 3rd to 5th elements using the following tuple.
acc_schools = ("Duke", "Notre Dame", "UNC", "NCSU", "Wake Forest", "Clemson")