• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

In Out Code

Your comprehensive guide to optimized code

  • Data Structures
  • Python
    • Control Flow
    • HackerRank
    • Input and Output
    • Modules
  • AWS

Python Tuples | Expert Guide with Code Samples

You are here: Home / Data Structures / Python Tuples | Expert Guide with Code Samples

May 14, 2019 by Daniel Andrews

What is a Tuple in Python?

A tuple is one of Python’s sequence data types, containing a comma separated list of values, often enclosed in parentheses. The parentheses are optional, but it’s good practice to include them.

Tuples are immutable, meaning their values cannot be modified after creation. However, tuples can contain mutable objects, such as strings and lists.

As with lists, the index of a tuple starts at 0. Tuples are almost identical to lists, except for using round instead of square brackets. Tuples are also immutable, whereas lists are mutable.

This guide walks you through everything you need to implement tuples in Python, with clear, commented code samples.

The following sections are included:

  • Create a tuple
  • Access a tuple
  • Update a tuple
  • Delete from a tuple
  • Test tuple membership
  • When to use a tuple instead of a list
  • Packing, unpacking and assignment
  • Concatenation and repetition
  • Tuples and in-built functions
  • Tuple methods
  • Nested tuples
  • Errors and exceptions

Create a Tuple

You have two main options for creating a tuple in Python:

  1. Using packing
  2. Using the python() constructor
1. Packing
# Different methods of creating tuples using packing
tuple1 = ("value1","value2","value3","value4")
tuple2 = (1,2,3,4,5)
tuple3 = 1,2,3,4,5
print(tuple1)
print(tuple2)
print(tuple3)
Output:
('value1', 'value2', 'value3', 'value4')
(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5)

If you would like to create an empty tuple, or a tuple with only one value, you can do so using the following syntax:

# Empty tuple created using a pair of empty parentheses
tupleEmpty = ()
print(tupleEmpty)

# Tuple containing a single value
tupleSingle = ("value1",)
print(tupleSingle)
Output:
()
('value1',)
2. Using the python() constructor
# Create a tuple using the tuple() constructor
tuple2 = tuple((6,7,8,9))
print("tuple((6,7,8,9)) =", tuple2)
Output:
tuple((6,7,8,9)) = (6, 7, 8, 9)

Access a Tuple

Elements in a tuple can be accessed in one of 3 ways:

  1. Unpacking
  2. Iteration in a for loop
  3. Indexing and slicing

1. Unpacking

If you need to split out elements of a tuple and assign them to individual variables, you can do so using unpacking. The number of variables on the left must match the number of elements in the tuple.

# Create a tuple using packing
tuple1 = ("value1","value2","value3","value4")

# Print the packed tuple
print("tuple1 before unpacking: ", tuple1)

# Unpack the tuple to 4 variables
print("Variable values after unpacking:")
val1, val2, val3, val4 = tuple1
Output:
tuple1 before unpacking:  ('value1', 'value2', 'value3', 'value4')

Variable values after unpacking:
val1 =  value1
val2 =  value2
val3 =  value3
val4 =  value4

2. Iteration in a for loop

# Iterate through elements in a tuple
tuple1 = ("value1","value2","value3","value4")
for x in tuple1:
    print(x)
Output:
value1
value2
value3
value4

3. Indexing and slicing

# Access tuple element by index
tuple1 = ("value1","value2","value3","value4")
print(tuple1[0])
Output:
value1
# Access multiple tuple elements by slicing
tuple1 = ("value1","value2","value3","value4")
print("tuple1[1:3] = ", tuple1[1:3])
print("tuple1[-1] = ", tuple1[-1])
Output:
tuple1[1:3] =  ('value2', 'value3')
tuple1[-1] =  value4

As with a list, elements can be accessed by positive and negative indexing. This is also useful for reversing the items in a tuple.

# Reversing items in a tuple
tuple1 = ("value1","value2","value3","value4")
tupleRev = tuple1[::-1]
print("tuple1 in original order:", tuple1)
print("tuple1 in reverse order:", tupleRev)
Output:
tuple1 in original order: ('value1', 'value2', 'value3', 'value4')
tuple1 in reverse order: ('value4', 'value3', 'value2', 'value1')

Update a Tuple

Tuples are immutable, meaning its structure cannot be changed after it is created. But if an element of the tuple is a mutable type, such as a list, then you can modify the structure of that element.

Example 1: Append item to a list inside a tuple
# Create a tuple containing a list
tup1 = (1, 2, 3, ["a", "b", "c"])
print("tup1 = {}".format(tup1))

# Append an item to the list
tup1[3].append("d")

# Display tup1, showing "d" has been added
print("tup1[3].append('d') = {}".format(tup1))
Output:
tup1 = (1, 2, 3, ['a', 'b', 'c'])
tup1[3].append('d') = (1, 2, 3, ['a', 'b', 'c', 'd'])

Delete from a Tuple

Tuples are immutable, meaning you cannot delete individual items. You can only delete the tuple completely, using the del keyword.

# Create a tuple, print it, delete it, then check if it exists
tuple1 = ("value1","value2","value3","value4")
print(tuple1)

del(tuple1)

# This will raise an error, because tuple1 no longer exists
print(tuple1)
Output:
('value1', 'value2', 'value3', 'value4')
Traceback (most recent call last):

  File "", line 7, in 
    print(tuple1)

NameError: name 'tuple1' is not defined

Test Tuple Membership

If you want to check whether or not a value exists in a tuple, you can use the in and not in keywords.

Checking tuple membership using in:

# Checking if a tuple contains the value "test7"
tuple1 = ("value1","value2","value3","value4")
if "value1" in tuple1:
    print("value1 is in tuple1")

# To simply return whether the condition is true or false
print("test7" in tuple1)
Output:
value1 is in tuple1
False

Checking tuple membership using not in:

# Checking if a tuple contains the value "test7"
tuple1 = ("value1","value2","value3","value4")
if "test7" not in tuple1:
    print("test7 is not in tuple1")

# To simply return whether the condition is true or false
print("test7" not in tuple1)
Output:
test7 is not in tuple1
True

When to Use a Tuple Instead of a List

  1. When you don’t want the items to be modified. Tuples protect against accidental modification.
  2. When you need to use a collection for the key of a dictionary. Dictionary keys must be immutable, which is why a list cannot be used.

Packing, Unpacking and Assignment

When items are assigned to a single tuple, this is called packing, because it’s as if the objects were “packed” into the object.

# Pack the values 1,2,3,4 into tuple1
tuple1 = (1, 2, 3, 4)

print("Value at position 0:", tuple1[0])
print("Value at position 1:", tuple1[1])
print("Value at position 2:", tuple1[2])
print("Value at position 3:", tuple1[3])
Output:
Value at position 0: 1
Value at position 1: 2
Value at position 2: 3
Value at position 3: 4
Unpacking

Unpacking is essentially the reverse of this process, where a “packed” object has its values split out and assigned to individual objects.

Note: During unpacking, the number of variables on the left must match the number of values in the tuple.

# Pack the values 1,2,3,4 into tuple1
tuple1 = (1, 2, 3, 4)

# Unpack the values from tuple1 into 1,2,3,4
(p1, p2, p3, p4) = tuple1

print("Value of p1:", p1)
print("Value of p2:", p2)
print("Value of p3:", p3)
print("Value of p4:", p4)
Output:
Value of p1: 1
Value of p2: 2
Value of p3: 3
Value of p4: 4

Packing and unpacking can also be combined in a single compound statement, which would have avoided the creation of the tuple1 object in the example above and given us the same result.

# Combine packing and unpacking in a single compound statement
(p1, p2, p3, p4) = (1, 2, 3, 4)

print("Value of p1:", p1)
print("Value of p2:", p2)
print("Value of p3:", p3)
print("Value of p4:", p4)
Output:
Value of p1: 1
Value of p2: 2
Value of p3: 3
Value of p4: 4

The same result can be achieved without using parentheses around the variables and values in the tuple. For clarity, it often makes sense to leave them in.

# Compound statement without parentheses
p1, p2, p3, p4 = 1, 2, 3, 4

print("Value of p1:", p1)
print("Value of p2:", p2)
print("Value of p3:", p3)
print("Value of p4:", p4)
Output:
Value of p1: 1
Value of p2: 2
Value of p3: 3
Value of p4: 4
Assignment

To save storing values in temporary variables, Python tuples support reassignment. This is where you can effectively swap the values contained within two variables.

# Create variables x and y, and assign values
x = 1
y = 2

# Perform the reassignment
y, x = x, y

print("The value of x is: ", x)
print("The value of y is: ", y)
Output:
The value of x is:  2
The value of y is:  1

The values have now been reversed. The same can be applied with any number of variables, as long as the number of variables on the left and right is equal.


Concatenation and Repetition

Once a tuple is created, you cannot add or remove items from it. You can combine multiple tuples using concatenation, but this will create an entirely new tuple.

Using + to combine multiple tuples:

# Create two separate tuples, then combine them to create a new tuple
tuple1 = (1,4,2,3)
tuple2 = (5,6,7)
tuple3 = tuple1 + tuple2
print("tuple1 + tuple2 =", tuple3)
Output:
tuple1 + tuple2 = (1, 4, 2, 3, 5, 6, 7)

Repetition can be performed in the same way you would with string sequences.

# Create a new tuple by repeating a single-item tuple 5 times
tupleRep = ("test1",)*5
print("(test1, ) * 5 =", tupleRep)
Output:
(test1, ) * 5 = ('test1', 'test1', 'test1', 'test1', 'test1')

Tuples and In-built Functions

Python has a wide range of in-built functions that can prove useful when working with tuples. This includes len(), max(), min() and sorted().

len()

len() returns the number of elements in a tuple.

# Check the number of items in tuple1
tuple1 = ("value1","value2","value3","value4")
print("len() of tuple1 =", len(tuple1))
Output:
len() of tuple1 = 4
max()

max() returns the maximum value from a tuple.

# Check the maximum value in tuple1
tuple1 = (1,4,5,8,900,5)
print("max() of tuple1 =", max(tuple1))
Output:
max() of tuple1 = 900
min()

min() returns the minimum value from a tuple.

# Check the minimum value in tuple1
tuple1 = (45,1,4,5,8,900)
print("min() of tuple1 =", min(tuple1))
Output:
min() of tuple1 = 1
sorted()

sorted() builds a new sorted list from an iterable, which in this case will be a tuple.

# Create a tuple to sort into a list
tuple1 = (45,1,4,5,8,900)

# Sort the tuple
x = sorted(tuple1)

# Reverse sort the tuple
xr = sorted(tuple1, reverse=True)

# Print the resulting object
print("sorted(tuple1) =", x)

# Print the resulting object in reverse order
print("sorted(tuple1, reverse=True) =", xr)
Output:
sorted(tuple1) = [1, 4, 5, 8, 45, 900]
sorted(tuple1, reverse=True) = [900, 45, 8, 5, 4, 1]

Tuple Methods

Python only has two methods that can be used with tuples:

  1. count()
  2. index()
1. count(x)

The count() method of a Python tuple returns the number of times a specified value appears.

# Create and populate a tuple to test with
tuple1 = (1, 2, 5, 6, 7, 7, 2, 2, 2)

# Print our count()
print("Number of times 2 appears in tuple1 = ", tuple1.count(2))
Output:
Number of times 2 appears in tuple1 =  4
2. index(x)

The index() method of a Python tuple searches for a specified value and returns the location of its first occurrence. If no value is found, index() raises an exception.

# Create and populate a tuple to test with
tuple1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

# Find first occurrence of 8 in tuple1
print("8 first appears in tuple1 at position: ", tuple1.index(8))
Output:
8 first appears in tuple1 at position:  3

Nested Tuples

As with Python’s other built-in collections, such as lists and dictionaries, it’s possible to create a nested tuple. This is where one or more of the elements in a tuple is a tuple.

# Create a nested tuple
tup1 = 1, 2, 3, ((1, "a"), (2, "b"), (3, "c"))
print("tup1 = {}".format(tup1))
Output:
tup1 = (1, 2, 3, ((1, 'a'), (2, 'b'), (3, 'c')))

To access the elements inside the nested tuple, you can use unpacking.

# Create a nested tuple
tup1 = 1, 2, 3, ((1, "a"), (2, "b"), (3, "c"))
print("tup1 = {}".format(tup1))

# Unpack the main tuple
item1, item2, item3, item4 = tup1
print("Item 1 = {}".format(item1))
print("Item 2 = {}".format(item2))
print("Item 3 = {}".format(item3))

# Unpack the nested tuple
for nested in item4:
    number, letter = nested
    print("Nested item {0} = {0}, {1}".format(number, letter))
Output:
tup1 = (1, 2, 3, ((1, 'a'), (2, 'b'), (3, 'c')))
Item 1 = 1
Item 2 = 2
Item 3 = 3
Nested item 1 = 1, a
Nested item 2 = 2, b
Nested item 3 = 3, c

Errors and Exceptions

Listed below are the most common errors and exceptions you’ll encounter when working with tuples in Python.

  • When you try to access a tuple that no longer exists. e.g. after deleting it using del
  • Accessing an index in the tuple that doesn’t exist
  • Attempting to unpack a tuple to a number of items that doesn’t match the length of the tuple

Category iconData Structures Tag iconPython Tuple

About Daniel Andrews

Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.

Primary Sidebar

48-Hour Flash Sale. Online courses as low as $12.99

Categories

  • AWS (4)
  • Concepts (1)
  • Control Flow (1)
  • Data Structures (9)
  • HackerRank (1)
  • Input and Output (1)
  • LeetCode (1)
  • Modules (1)
  • Operators (1)
  • Python (2)
Udemy.com Homepage 300x250

Footer

Recent Posts

  • How to Setup Neo4j on AWS ECS (EC2)
  • How to Setup Neo4j on AWS EC2
  • How to List AWS S3 Bucket Names and Prefixes
  • Amazon Redshift Tutorial (AWS)
  • Big O: How to Calculate Time and Space Complexity

.