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.

By the end of this notebook, you will:

  • create tuples and explain how they differ from lists in terms of mutability and hashability

  • apply sequence operations to tuples, recognizing that len(), indexing, and slicing work identically across strings, lists, and tuples

  • use tuple unpacking and the collector operator (*) to assign multiple variables in a single statement

  • explain when to choose a tuple over a list or string based on mutability, hashability, and function return semantics

  • apply tuple unpacking to financial data records, time series, and function arguments

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 parentheses 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.

1market_regimes = ['Bull', 'Bear', 'Stagnant', 'Recovery']
2tuple(market_regimes)
('Bull', 'Bear', 'Stagnant', 'Recovery')

14.1. Combining Tuples +#

Just as we use + to concatenate strings and lists, we can also combine tuples with this operator

1('Bull','Bear','Stagnant') + ('Recovery',)
('Bull', 'Bear', 'Stagnant', 'Recovery')

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('Bull','Bear','Stagnant') + ('Recovery')         #Raises a TypeError
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 ('Bull','Bear','Stagnant') + ('Recovery')         #Raises a TypeError

TypeError: can only concatenate tuple (not "str") to tuple

As you can see, Python used the parentheses 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)         # parentheses are optional for tuples.
2print(f"quotient={quotient:d}, remainder={remainder:d}")
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(f"a={a:d}, b={b:d}")
 5
 6# for other languages without parallel assignment
 7swap = a
 8a = b
 9b = swap
10print(f"a={a:d}, b={b:d}")
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(f"name={name:s}, domain={domain:s}")
name=administrator, domain=thedomain.com

14.5. Tuple Assignment vs. Tuple Unpacking#

In Python, the terms “tuple assignment” and “tuple unpacking” are often used interchangeably, but they represent slightly different perspectives of the same operation.

Tuple Assignment refers to assigning values on the right-hand side to variables on the left-hand side. This is the fundamental operation we’ve already seen:

1# Basic tuple assignment
2coordinates = (10.5, 20.7)
3x, y = coordinates  # Assigning values from the tuple to individual variables

Tuple Unpacking emphasizes the extraction of individual values from the tuple structure. While the operation is the same, this terminology focuses on breaking down the tuple into its components:

1# Same operation, viewed as "unpacking" the tuple
2data_point = (1612.43, 18.2, 7.1)
3price, volume, volatility = data_point  # Unpacking the data into named variables

Tuple unpacking is particularly valuable because it:

  • Makes code more readable by assigning meaningful names to values

  • Reduces the need for indexing (e.g., data_point[0], data_point[1])

  • Enforces the expected structure of data (raises an error if the number of variables doesn’t match)

14.5.1. From Basic to Advanced Unpacking#

Basic tuple unpacking requires the number of variables on the left side to exactly match the number of elements in the tuple. But what if you don’t know how many elements a tuple contains, or you’re only interested in specific positions?

This is where Python’s advanced unpacking features come into play, particularly the collector operator.

14.6. Advanced Tuple Unpacking#

Python provides powerful features for more flexible unpacking scenarios that go beyond the basic pattern of matching exactly one variable to one element.

14.6.1. Partial Unpacking with the Collector Operator (*)#

While basic tuple unpacking is powerful, it has a limitation: the number of variables must exactly match the number of values in the tuple. If you have fewer or more variables than values, Python raises a ValueError.

This is where the collector operator (*) comes in. It allows you to collect multiple values into a single list variable, providing flexibility when:

  1. You don’t know exactly how many items are in a tuple

  2. You only care about certain positions (e.g., first, last)

  3. You want to split a sequence into “head” and “rest” or “init” and “tail” segments

Sometimes you may want to unpack only specific elements from a tuple while collecting the rest into a separate variable:

 1# Basic tuple unpacking
 2a, b, c = (1, 2, 3)
 3print(f"a={a}, b={b}, c={c}")  # a=1, b=2, c=3
 4
 5# Using the collector operator to gather remaining elements
 6first, *rest = (10, 20, 30, 40, 50)
 7print(f"first={first}, rest={rest}")  # first=10, rest=[20, 30, 40, 50]
 8
 9# The collector doesn't have to be at the beginning
10head, *middle, tail = (10, 20, 30, 40, 50)
11print(f"head={head}, middle={middle}, tail={tail}")  # head=10, middle=[20, 30, 40], tail=50
12
13# Collector with minimal elements
14first, *rest = (10,)  
15print(f"first={first}, rest={rest}")  # first=10, rest=[]
a=1, b=2, c=3
first=10, rest=[20, 30, 40, 50]
head=10, middle=[20, 30, 40], tail=50
first=10, rest=[]

Note: The collected elements are always returned as a list, not a tuple, regardless of the original data structure.

14.6.2. Key Points About the Collector Operator#

Note: The “collector operator” (*) is also known as “extended iterable unpacking” or “starred assignment” in the Python documentation (PEP 3132).

  1. You can only use one collector operator in a single unpacking assignment.

  2. The collector variable will always be a list, even if the original structure is a tuple.

  3. If there are no elements to collect, the collector variable will be an empty list.

  4. The collector operator works with any iterable, not just tuples.

14.6.3. From Variable Assignment to Function Arguments#

So far, we’ve seen how the collector operator works with tuple unpacking in assignment statements. But Python’s unpacking mechanism is even more versatile - it extends beyond assignment to function calls.

When used on the right-hand side of assignments or in function calls, the collector operator serves a different purpose: it expands a sequence into individual elements. This is sometimes called “packing” or “spreading” the sequence.

14.6.4. Unpacking in Function Calls#

The collector operator can be used on the right side of assignments to unpack sequences into function arguments:

 1def analyze_portfolio(stock1, stock2, stock3):
 2    print(f"Analyzing {stock1}, {stock2}, and {stock3}")
 3
 4tech_stocks = ("AAPL", "MSFT", "GOOG")
 5analyze_portfolio(*tech_stocks)  # Unpacks tuple into the three arguments
 6
 7
 8# You can also use the collector operator when creating new tuples:
 9
10dow_stocks = ("JPM", "GS", "V")
11nasdaq_stocks = ("AAPL", "MSFT", "GOOG")
12
13# Combining tuples with the collector operator
14all_stocks = (*dow_stocks, *nasdaq_stocks)
15print(all_stocks)  # ('JPM', 'GS', 'V', 'AAPL', 'MSFT', 'GOOG')
16
17# Adding individual elements along with unpacked tuples
18watch_list = ("TSLA", *dow_stocks, "AMZN", *nasdaq_stocks)
Analyzing AAPL, MSFT, and GOOG
('JPM', 'GS', 'V', 'AAPL', 'MSFT', 'GOOG')

14.6.5. Connecting Theory to Practice: Financial Applications#

Having covered the mechanics of tuple unpacking and the collector operator, let’s see how these concepts apply specifically to financial programming scenarios. These patterns are particularly valuable when working with time series data, financial records, and market analysis.

14.6.6. Practical Applications in Finance#

Tuple unpacking with the collector operator is particularly useful in financial applications:

 1# Unpacking time series data where you need the latest point and historical values
 2daily_closing_prices = (
 3    # Starting with most recent date first (common in financial data)
 4    ("2025-04-23", 142.67),
 5    ("2025-04-22", 143.12),
 6    ("2025-04-21", 141.88),
 7    ("2025-04-18", 140.56),
 8    ("2025-04-17", 139.45),
 9    ("2025-04-16", 140.23))
10latest, *historical = daily_closing_prices
11print(f"Latest price: {latest}, Historical trend: {historical}")
12
13
14# Sample stock_data_record examples
15# Format: (ticker, current_price, volume, PE_ratio, market_cap, beta, sector)
16
17# Single stock record example
18stock_data_record = ("AMZN", 182.34, 12453678, 41.8, 1890000000000, 1.23, "Technology")
19
20# Example of using unpacking with a single record
21ticker, price, *metrics = stock_data_record
22print(f"Stock: {ticker}")
23print(f"Current Price: ${price}")
24print(f"Additional metrics: Volume={metrics[0]}, PE={metrics[1]}, Market Cap=${metrics[2]/1e9}B, Beta={metrics[3]}, Sector={metrics[4]}")
25
26# Sample stock_returns data
27# Format: list of monthly returns (percentages) for different stocks
28
29# Single stock returns over 12 months
30stock_returns = (4.2, -1.7, 3.5, 0.8, -2.3, 5.1, 1.2, -0.5, 2.8, 3.7, -1.1, 2.5)
31
32# Example of splitting into training and test data (common in financial modeling)
33*training_data, test_data = stock_returns
34print(f"Training data (first 11 months): {training_data}")
35print(f"Test data (last month): {test_data}")
Latest price: ('2025-04-23', 142.67), Historical trend: [('2025-04-22', 143.12), ('2025-04-21', 141.88), ('2025-04-18', 140.56), ('2025-04-17', 139.45), ('2025-04-16', 140.23)]
Stock: AMZN
Current Price: $182.34
Additional metrics: Volume=12453678, PE=41.8, Market Cap=$1890.0B, Beta=1.23, Sector=Technology
Training data (first 11 months): [4.2, -1.7, 3.5, 0.8, -2.3, 5.1, 1.2, -0.5, 2.8, 3.7, -1.1]
Test data (last month): 2.5

14.7. 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.8. 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.9. Review Questions#

  1. What are the differences between lists and tuples?

  2. Explain how multiple values can be returned from a function in Python.

  3. How are tuples created? Provide examples.

  4. Explain how sequences work across strings, lists, and tuples.

  5. How do you access elements in a tuple? Provide examples.

  6. Can a tuple contain mutable objects like lists? Explain.

answers

14.10. Exercises#

  1. 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.

  2. Test if the stock symbol “BAC” is in the data tuple.

  3. Create a new tuple of the 3rd to 5th elements using the following tuple.

    acc_schools = ("Duke", "Notre Dame", "UNC", "NCSU", "Wake Forest", "Clemson")
    
  4. Create a tuple of monthly returns for a stock. Use tuple unpacking with the collector operator to separate the first quarter, middle quarters, and last quarter returns.

  5. Write a function that accepts any number of stock prices and returns their average price. Use the collector operator to unpack a tuple of stock prices into the function call.

  6. Given a tuple of (stock_name, current_price, high_52week, low_52week, dividend_yield), use tuple unpacking to extract the stock name and create a list of just the numerical values.

Exercise answers