Tuple Examples
This page was last reviewed on Apr 14, 2023.
Dot Net Perls
Tuple. Python tuples are values—they never change. Suppose an element has a shape and a color. This forms a tuple pair. Logically this information is a single unit.
With tuples, we have a simple way to group elements together in Python programs. We can build up lists of tuples, or use them in dictionaries.
First example. A tuple is immutable—this is important to consider. It cannot be changed after created, so the creation syntax must be used often.
Note For a tuple with multiple elements, use a comma between elements. No ending comma is needed.
Note 2 To get the number of elements in a tuple, use the len built-in. The first element can be accessed at index 0 (like a list).
# Create 3-element tuple. items = ("bird", 100, False) print("TUPLE:", items) print("LEN:", len(items)) print("FIRST:", items[0])
TUPLE: ('bird', 100, False) LEN: 3 FIRST: bird
Immutable. An immutable object cannot be changed. Once created it always has the same values. A tuple is immutable. Here we attempt to assign the first element in the tuple.
But This is invalid. When executed, the Python runtime will report a TypeError.
Tip To make a new, changed tuple, we would need to create a new tuple. We could specify that some items have the same values.
tuple = ('cat', 'dog', 'mouse') # This causes an error. tuple[0] = 'feline'
TypeError: 'tuple' object does not support item assignment
Pack, unpack. Tuples can be packed and unpacked. In packing, we place values into a new tuple. And in unpacking we extract those values back into variables.
Note This syntax form creates elegant and small programs. In this program we pack two strings into a tuple.
Then We initialize two variables to those two packed values. The variables act like any other variable.
# Create packed tuple. pair = ("dog", "cat") # Unpack tuple. (key, value) = pair # Display unpacked variables. print(key) print(value)
dog cat
No parentheses. Tuples are typically specified with surrounding parentheses chars. But suppose you are a wild one. You can just use a comma. The tuple is inferred.
# A trailing comma indicates a tuple. one_item = "cat", # A tuple can be specified with no parentheses. two_items = "cat", "dog" print(one_item) print(two_items)
('cat',) ('cat', 'dog')
Add, multiply. A tuple is not a number. But it can be added to or multiplied. By adding two tuples, they are concatenated. One is put after the other.
And By multiplying a tuple with a number, we add the tuple to itself a certain number of times.
Warning This syntax form can become somewhat confusing. I have not used it often on tuples.
checks = (10, 20, 30) # Add two tuples. more = checks + checks print(more) # Multiply tuple. total = checks * 3 print(total)
(10, 20, 30, 10, 20, 30) (10, 20, 30, 10, 20, 30, 10, 20, 30)
Max, min. The max and min functions can be used on tuples. These functions locate the item that would be sorted last (max) or sorted first (min).
# Max and min for strings. friends = ("sandy", "michael", "aaron", "stacy") print(max(friends)) print(min(friends)) # Max and min for numbers. earnings = (1000, 2000, 500, 4000) print(max(earnings)) print(min(earnings))
stacy aaron 4000 500
In keyword. This example creates a two-element tuple (a pair). It searches the tuple for the string "cat". It then searches for "bird", but this string does not exist.
Note With the in-keyword, we can search a tuple. We use in as part of an if-statement. And we can combine in with not—this is "not in".
pair = ("dog", "cat") # Search for a value. if "cat" in pair: print("Cat found") # Search for a value not present. if "bird" not in pair: print("Bird not found")
Cat found Bird not found
Slice. A tuple can be sliced. The slice notation uses a colon. On the left side of the colon, we have the starting index. If no starting index is present, the program uses 0.
And On the right side of the colon, we have the ending index. If no ending index is present, the last index possible is used.
Note Slicing creates a new tuple. A slice that specifies no indexes is a simple way to copy a tuple.
values = (1, 3, 5, 7, 9, 11, 13) # Copy the tuple. print(values[:]) # Copy all values at index 1 or more. print(values[1:]) # Copy one value, starting at first. print(values[:1]) # Copy values from index 2 to 4. print(values[2:4])
(1, 3, 5, 7, 9, 11, 13) (3, 5, 7, 9, 11, 13) (1,) (5, 7)
Index. This gets the index of an element. Here we search for the value "dog," and get the index 1 (the second position). If we use index() on a value that is not found, an error results.
Tip Consider the in operator before calling index() on a value that might not exist. This prevents a possible exception.
# Three-item tuple. items = ("cat", "dog", "bird") # Get index of element with value "dog". index = items.index("dog") print(index, items[index])
1 dog
Count. This returns the number of elements with a specific value in a tuple. If you need to get the total length of the tuple, please use len. Count only counts certain values.
values = (1, 2, 2, 3, 3, 3) print(values.count(1)) print(values.count(3)) # There are no 100 values, so this returns 0. print(values.count(100))
1 3 0
Keys, dictionary. We next use a tuple as a dictionary key. Dictionaries can use tuple keys without worrying about them changing. Here we use the pair of values 1 and 2 to look up a value.
Tip You can use tuples in this way to create a two-dimensional dictionary. Use a tuple to represent X and Y coordinates.
# A tuple with two numbers. pair = (1, 2) # Create a dictionary. # ... Use the tuple as a key. dict = {} dict[pair] = "Python" # Access the dictionary using a tuple. print(dict[(1, 2)])
Convert. A tuple cannot be modified. But a list can be changed in many ways. For this reason we often need to convert a tuple into a list.
Detail The list built-in accepts a tuple as its argument. Here we use sort() on the resulting list.
Finally In the program, we convert the list back into a tuple. This is done with the tuple() function.
Here We see that a list has square brackets. A tuple has round ones. This is an important part of Python's syntax.
# Tuple containing unsorted odd numbers. odds = (9, 5, 11) # Convert to list and sort. list = list(odds) list.sort() print(list) # Convert back to tuple. sorted_odds = tuple(list) print(sorted_odds)
[5, 9, 11] (5, 9, 11)
Enumerate. This is a built-in method. Enumerate() returns a tuple of an index and the element value at that index. It is often used on a list.
Here We use enumerate on a list of strings. We can access the tuple, or directly unpack the tuple in the for-statement.
values = ["meow", "bark", "chirp"] # Use enumerate on list. for pair in enumerate(values): # The pair is a 2-tuple. print(pair) # Unpack enumerate's results in for-loop. for index, value in enumerate(values): # We have already unpacked the tuple. print(str(index) + "..." + value)
(0, 'meow') (1, 'bark') (2, 'chirp') 0...meow 1...bark 2...chirp
List of tuples. Let us examine a practical example. This program divides a string into a list of tuples. Each tuple has adjacent characters from the string.
Start We use the range built-in to iterate over the string, with a step of 2. We start at index 1 to avoid the first char.
Then We call append() on the list (called "pairs") and as the argument to append, we create a two-element tuple (a pair).
value = "abcdefgh" pairs = [] # Loop over string. # ... Use step of 2 in range built-in. # ... Extract pairs of letters into a list of tuples. for i in range(1, len(value), 2): one = value[i - 1] two = value[i] pairs.append((one, two)) # Display list of tuple pairs. for pair in pairs: print(pair)
('a', 'b') ('c', 'd') ('e', 'f') ('g', 'h')
Swap. To flip or swap variables, we do not need a temporary variable. We can use a tuple unpacking expression. We assign each variable to the other one in a single statement.
left = "cat" right = "dog" print("LEFT", left) print("RIGHT", right) print(":::FLIP:::") # Use tuple unpacking to flip variables. left, right = right, left print("LEFT", left) print("RIGHT", right)
LEFT cat RIGHT dog :::FLIP::: LEFT dog RIGHT cat
Benchmark. How do we choose between the syntax forms for tuples? In this benchmark we test two ways of assigning variables to values in a tuple. We unpack tuples.
Version 1 This version of the program uses a single statement to unpack an existing tuple.
Version 2 This version assigns to the elements in a tuple using the "[" and "]" syntax.
Result Version 1, which unpacks the tuple in a single statement, is somewhat faster.
Note In Python, the number of statements often influences greatly the results. This may change as more advanced compilers appear.
import time pair = (1, 2) print(time.time()) # Version 1: unpack tuple. i = 0 while i < 10000000: (a, b) = pair i = i + 1 print(time.time()) # Version 2: assign variables to tuple separately. i = 0 while i < 10000000: a = pair[0] b = pair[1] i = i + 1 print(time.time())
1345673733.21 1345673737.12 (Unpack: 3.91 s) 1345673742.12 (Assign: 5.00 s)
Namedtuple. In normal tuples, fields have no names. With namedtuple, a type from the collections module, we can provide names to a tuple's fields.
A summary. With tuples, we have access to many helpful methods. Tuples are key to other important types, such as dictionary. And they are used, to some advantage, within lists.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 14, 2023 (edit).
© 2007-2024 Sam Allen.