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.
A tuple is immutable—this is important to consider. It cannot be changed after created, so the creation syntax must be used often.
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
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.
TypeError
.tuple = ('cat', 'dog', 'mouse') # This causes an error. tuple[0] = 'feline'TypeError: 'tuple' object does not support item assignment
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.
# Create packed tuple. pair = ("dog", "cat") # Unpack tuple. (key, value) = pair # Display unpacked variables. print(key) print(value)dog cat
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')
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.
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
, minThe 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
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.
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
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.
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.
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
, dictionaryWe 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.
# 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)])Python
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.
sort()
on the resulting list.tuple()
function.# 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)
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.
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 tuplesLet us examine a practical example. This program divides a string
into a list of tuples. Each tuple has adjacent characters from the string
.
string
, with a step of 2. We start at index 1 to avoid the first char
.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')
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
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.
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)
In normal tuples, fields have no names. With namedtuple, a type from the collections module, we can provide names to a tuple's fields.
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.