Python Tuple

What is Python Tuple?

A tuple is an ordered collection of values.

Tuples are a lot like lists:

  • Tuples are ordered – Tuples maintains a left-to-right positional ordering among the items they contain.
  • Accessed by index – Items in a tuple can be accessed using an index.
  • Tuples can contain any sort of object – It can be numbers, strings, lists and even other tuples.

except:

  • Tuples are immutable – you can’t add, delete, or change items after the tuple is defined.

Create a Tuple

You can create a tuple by placing a comma-separated sequence of items in parentheses ().

Example:

# A tuple of integers
T = (1, 2, 3)
# A tuple of strings
T = ('red', 'green', 'blue')

The items of a tuple don’t have to be the same type. The following tuple contains an integer, a string, a float, and a boolean.

Example:

# A tuple with mixed datatypes
T = (1, 'abc', 1.23, True)

A tuple containing zero items is called an empty tuple and you can create one with empty
brackets ()

Example:

# An empty tuple
T = ()

Syntactically, a tuple is just a comma-separated list of values.

Example:

# A tuple without parentheses
T = 1, 'abc', 1.23, True

You don’t need the parentheses to create a tuple. It’s the trailing commas that really define a tuple.

But using them doesn’t hurt; also they help make the tuple more visible.

Singleton Tuple

If you have only one value in a tuple, you can indicate this by including a trailing comma , just before the closing parentheses.

Example: Create a single item tuple

T = (4,)
print(type(T))  # <type 'tuple'>

Otherwise, Python will think you’ve just typed a value inside regular parentheses.

Example: Not a tuple

T = (4)
print(type(T))  # <type 'int'>

The tuple() Constructor

You can convert other data types to tuple using Python’s tuple() constructor.

Example: Convert a list to a tuple

T = tuple([1, 2, 3])
print(T)    # (1, 2, 3)

Example: Convert a string to a tuple of one-character strings

T = tuple('abc')
print(T)    # ('a', 'b', 'c')

Nested Tuples

A tuple can contain sub-tuple, which in turn can contain sub-tuples themselves, and so on. This is known as nested tuple.

You can use them to arrange data into hierarchical structures.

Example: Create nested tuples

T = ('red', ('green', 'blue'), 'yellow')

Tuple Packing & Unpacking

Tuple Packing

When a tuple is created, the items in the tuple are packed together into the object.

Example:

T = ('red', 'green', 'blue', 'cyan')
print(T)    # ('red', 'green', 'blue', 'cyan')

In above example, the values ‘red’, ‘green’, ‘blue’ and ‘cyan’ are packed together in a tuple.

Tuple Packing

Tuple Unpacking

When a packed tuple is assigned to a new tuple, the individual items are unpacked (assigned to the items of a new tuple).

Example:

T = ('red', 'green', 'blue', 'cyan')
(a, b, c, d) = T
print(a)    # red
print(b)    # green
print(c)    # blue
print(d)    # cyan

In above example, the tuple T is unpacked into a, b, c and d variables.

Tuple Unpacking

When unpacking, the number of variables on the left must match the number of items in the tuple.

Example: Common errors in tuple unpacking

# ValueError: too many values to unpack
T = ('red', 'green', 'blue', 'cyan')
(a, b) = T
# ValueError: need more than 3 values to unpack
T = ('red', 'green', 'blue')
(a, b, c, d) = T

Usage

Tuple unpacking comes handy when you want to swap values of two variables without using a temporary variable.

Example: Swap values of ‘a’ and ‘b’

a = 1
b = 99
a, b = b, a
print(a)    # 99
print(b)    # 1

While unpacking a tuple, the right side can be any kind of sequence (tuple, string or list).

Example: Split an email address into a user name and a domain

addr = 'bob@python.org'
user, domain = addr.split('@')

print(user)     # bob
print(domain)   # python.org

Access Tuple Items

You can access individual items in a tuple using an index in square brackets.

Note that tuple indexing starts from 0.

The indices for the elements in a tuple are illustrated as below:

Python Tuple Indexing

Example: Access 1st and 3rd items by positive index

T = ('red', 'green', 'blue', 'yellow', 'black')
print(T[0])     # red
print(T[2])     # blue

You can access a tuple by negative indexing as well.

Negative indexes count backward from the end of the tuple. So, T[-1] refers to the last item, T[-2] is the second-last, and so on.

Example: Access last and 2nd last items by negative index

T = ('red', 'green', 'blue', 'yellow', 'black')
print(T[-1])     # black
print(T[-2])     # yellow

Tuple Slicing

To access a range of items in a tuple, you need to slice a tuple using a slicing operator.

Tuple slicing is similar to list slicing.

Example:

T = ('a', 'b', 'c', 'd', 'e', 'f')

print(T[2:5])		# ('c', 'd', 'e')
print(T[0:2])		# ('a', 'b')
print(T[3:-1])		# ('d', 'e')

Change Tuple Items

Tuples are immutable (unchangeable). Once a tuple is created, it cannot be modified.

Example: Tuples cannot be modofied

# TypeError: 'tuple' object does not support item assignment
T = ('red', 'green', 'blue')
T[0] = 'black'

The tuple immutability is applicable only to the top level of the tuple itself, not to its contents.

For example, a list inside a tuple can be changed as usual.

Example: Mutable item inside a tuple can be changed

# Modifying list inside tuple
T = (1, [2, 3], 4)
T[1][0] = 'xx'
print(T)    # (1, ['xx', 3], 4)

Delete a Tuple

Tuples cannot be modified, so obviously you cannot delete any item from it.

However, you can delete the tuple completely with del keyword.

Example: Delete a tuple completely with del keyword

T = ('red', 'green', 'blue')
del T

Tuple Concatenation & Repetition

Tuples can be joined using the concatenation operator + or Replication operator *

Example: Join tuples

# Concatenate
T = ('red', 'green', 'blue') + (1, 2, 3)
print(T)    # ('red', 'green', 'blue', 1, 2, 3)
# Replicate
T = ('red',) * 3
print(T)    # ('red', 'red', 'red')

Find Tuple Length

To find how many items a tuple has, use len() method.

Example: Find length of a tuple

T = ('red', 'green', 'blue')
print(len(T))   # 3

Check if item exists in a tuple

To determine whether a value is or isn’t in a tuple, you can use in and not in operators with if statement.

Example: Check if item exists in a tuple

# Check for presence
T = ('red', 'green', 'blue')
if 'red' in T:
    print('yes')
# Check for absence
T = ('red', 'green', 'blue')
if 'yellow' not in T:
    print('yes')

Iterate through a tuple

To iterate over the items of a tuple, use a simple for loop.

Example: Print each item in a tuple

T = ('red', 'green', 'blue')
for item in T:
    print(item)    # red green blue

Tuple Sorting

There are two methods to sort a tuple.

Method 1: Convert a tuple to a mutable object like list (using list constructor), gain access to a sorting method call (sort()) and convert it back to tuple.

Example: Sort a tuple by converting it to a list

T = ('cc', 'aa', 'dd', 'bb')
tmp = list(T)	# convert tuple to list
tmp.sort()		# sort list
T = tuple(tmp)	# convert list to tuple
print(T)    	# ('aa', 'bb', 'cc', 'dd')

Method 2: Use the built-in sorted() method that accepts any sequence object.

Example: Sort a tuple using built-in sorted() method

T = ('cc', 'aa', 'dd', 'bb')
print(tuple(sorted(T)))  # ('aa', 'bb', 'cc', 'dd')

Python Tuple Methods

Python has a set of built-in methods that you can call on tuple objects.

Python tuple Methods
MethodDescription
count()Returns the count of specified item in the tuple
index()Returns the index of first instance of the specified item

Built-in Functions with Tuple

Python also has a set of built-in functions that you can use with tuple objects.

Python Built-in Functions with Tuple
MethodDescription
all()Returns True if all tuple items are true
any()Returns True if any tuple item is true
enumerate()Takes a tuple and returns an enumerate object
len()Returns the number of items in the tuple
max()Returns the largest item of the tuple
min()Returns the smallest item of the tuple
sorted()Returns a sorted tuple
sum()Sums items of the tuple
tuple()Converts an iterable (list, string, set etc.) to a tuple