Python Tuple

Built-in Dictionary List Set Tuple Array Bytes Class Compression Console Convert Datetime Def Error File Generator If Itertools JIT Lambda Loop Map Math None Number Path Print Re Slice Sort Split String Urllib

Tuple

A tuple stores values. It is similar to a list but uses different syntax. With tuples we cannot change elements. This makes programs more predictable.
So tuples can be used as values:
unlike classes,
they never change.

Create

Let us start. We first revisit the concept of immutability. A tuple is immutable: it cannot be changed after created. For this reason, the creation syntax is important. We use parentheses "(" and ")" to create tuples.

Dots: colored circles

Zero elements:To create a tuple with zero elements, use only the two parentheses "()".

One element:For a tuple with one element, use a trailing comma. This helps Python tell that you don't mean an expression, such as (1 + 2).

Two elements:For a tuple with two or more elements, use a comma between elements. No ending comma is needed.

Based on:

Python 3

Python program that creates tuples

# Zero-element tuple
a = ()
# One-element tuple
b = ("one",)
# Two-element tuple
c = ("one", "two")

print(a)
print(len(a))

print(b)
print(len(b))

print(c)
print(len(c))

Output

()
0
('one',)
1
('one', 'two')
2

Immutable

Concept

In computer science, an immutable object cannot be changed. Once created it always has the same values. A tuple in Python is immutable. In this program, we attempt to assign the first element in the tuple to a new string value.

But:This is invalid. When executed, the Python runtime will report a TypeError.

Try

Note:To create a new, changed tuple, we would need to simply create a new tuple. We could specify that some items have the same values.

Python program that assigns tuple

tuple = ('cat', 'dog', 'mouse')

# This causes an error
tuple[0] = 'feline'

Result

TypeError: 'tuple' object does not support item assignment
Question

Why are tuples immutable? The concept of immutable objects is at first confusing. It also seems inefficient—why create more objects than necessary? But some objects are more efficient when they are immutable.

For example, in a dictionary tuples are used. We can access these two-element tuples directly. If these tuples could be changed, the original dictionary would become invalid. Our Python script would have hard-to-diagnose bugs.

However:With immutable tuples, a Python program would need to copy the tuple. The dictionary would never become invalid.

Assign

Note

In Python we have the concepts of packing and unpacking when using tuples. 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 then like any other variable.

Python program that assigns variables

# Create packed tuple
pair = ("dog", "cat")

# Unpack tuple
(key, value) = pair

# Display unpacked variables
print(key)
print(value)

Output

dog
cat

Add, multiply

Star, asterisk character

A tuple is not a number. But it can still be added to or multiplied in Python. By adding two tuples, they are concatenated—one is put after the other. And by multiplying, we add the tuple to itself a certain number of times.

Tip:As with direct addition, this makes the tuple longer. This syntax is a form of list comprehension syntax.

Python program that adds and multiples tuples

checks = (10, 20, 30)

# Add two tuples
more = checks + checks
print(more)

# Multiply tuple
total = checks * 3
print(total)

Output

(10, 20, 30, 10, 20, 30)
(10, 20, 30, 10, 20, 30, 10, 20, 30)
Syntax

This syntax form can become somewhat confusing. And in my experience I have not used it often on tuples. But it is nice to know it is there. It provides a way to create large tuples with only a few characters.

You cannot divide or subtract tuples. Out of curiosity I tried this and I received the TypeError with "unsupported operand type." As a reminder, an operand is a value on one side of an expression. It is part of an operation.

Max, min

Maximum and minimum values: height of buildings

As we have found, tuples in Python are similar to lists. The max and min methods can be used on tuples. These methods locate the item that would be sorted last (max) or sorted first (min).

List

For strings:The comparison performed is alphabetical—"able" comes before "zero". So "able" would be less than "zero".

For numbers:The comparison is numeric—10 comes before 20. These comparisons are logical.

On tuples, the max and min methods are helpful. This is particularly true because tuples cannot be sorted. They are immutable, and sorting changes the element order. These methods adhere to tuple usage patterns.

Python program that uses max and 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))

Output

stacy
aaron
4000
500

In

In keyword

This example script 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. The "not in" part of the expression evaluates to true.

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

In
Python program that searches tuples

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")

Output

Cat found
Bird not found

Slice

Array elements

Next, we learn that a tuple can be sliced. The slice notation in Python 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 your tuple.

Slice

As a developer, I find the slice syntax to be somewhat confusing. Many methods use the second argument as a count, not an ending index. But in Python we always refer to indexes in slicing notation.

Python that uses tuple slices

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])

Output

(1, 3, 5, 7, 9, 11, 13)
(3, 5, 7, 9, 11, 13)
(1,)
(5, 7)

Index

Index

With index(), we get the index of an element of a specific value. Here, we search for the value "dog" within the tuple, 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.

Python that uses index

# Three-item tuple.
items = ("cat", "dog", "bird")

# Get index of element with value "dog".
index = items.index("dog")
print(index, items[index])

Output

1 dog

Count

Steps

Count 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. If no matching values exist, it returns 0.

Python that uses count

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))

Output

1
3
0

Keys, dictionary

Key: used to access value

We next use a tuple as a dictionary key. Because tuples are immutable, dictionaries can use them as keys without worrying about them changing. Here, we use the pair of values 1 and 2 to look up a value in a dictionary.

Tip:You can use tuples in this way to create a two-dimensional dictionary. Use a tuple to represent X and Y coordinates.

Dictionary
Python that uses tuples as dictionary keys

# 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)])

Output

Python

Convert

Convert or change

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. In this program we convert a tuple to a list with the list() method.

Note:The list method accepts the tuple as its argument. We then use sort() on the list.

Finally:In the program, we convert the list back into a tuple. This is done with the tuple() method.

Convert

We see that a list has square brackets and a tuple has round ones. This is a core syntactic feature in the Python language. Most often programs use lists—they have more features.

Python that converts tuple and list

# 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
sortedOdds = tuple(list)
print(sortedOdds)

Output

[5, 9, 11]
(5, 9, 11)

Performance

Struct

How do we choose between the syntax forms for tuples? Are some syntax forms faster? 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.

Python that benchmarks tuple

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())

Result

1345673733.21
1345673737.12 (Unpack: 3.91 s)
1345673742.12 (Assign: 5.00 s)
Python language

Version 1, which unpacks the tuple in a single statement, is somewhat faster. In Python, the number of statements in micro-benchmarks often influences greatly the results. This may change as more advanced compilers appear.

JIT Tests

Typically:Versions of Python scripts that have fewer statements (fewer lines) tend to execute faster than ones with more lines.

Namedtuple

ABC: letters

In normal tuples, fields have no names. With namedtuple, a type from the collections module, we can provide names to a tuple's fields. This makes some programs easier to maintain.

Namedtuple

Summary

With tuples we have access to many (but not all) of the methods of a list. Tuples are key to other important types, such as dictionary.
And they are used,
to some advantage,
within lists. They are often combined with other types.

Python