Python Tuples: Create, Access, Slice, and Unpack

By 

Updated on

10 min read

Python Tuples

Python has several sequential data types that allow you to store collections of data in an organized and efficient way. The basic sequence types are strings, lists, tuples, and range objects.

This article will walk you through the basics of Python tuples. We will show you how to create a tuple, access elements, unpack a tuple, and more.

Tuples are similar to lists , with the main difference being that the lists are mutable while the tuples are immutable. This means that the tuples can not be changed after creation.

Tuples can store both heterogeneous and homogeneous data but are generally used to store collections of heterogeneous elements.

Creating Tuples

Tuples are created by placing the items inside a pair of round brackets (), separated by commas. They can have any number of items, which can be of different types. Here is an example:

py
colors = ('orange', 'white', 'green')

A tuple can have items with mixed data types. You can also declare nested tuples where one or more of its items are lists, tuples or dictionaries :

py
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))

Round brackets with no elements in between them denote an empty tuple:

py
my_tuple = ()

To create a tuple with only one element you must add a comma after the element:

py
my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)
output
<class 'int'>
<class 'tuple'>

Without the trailing comma, Python treats the round brackets as a grouping operator, so (1) is just the integer 1, not a tuple.

Tuples can be also constructed using the tuple() constructor:

py
colors_list = ['orange', 'white', 'green']
colors_tuple = tuple(colors_list)
print(type(colors_tuple))
output
<class 'tuple'>

Another way to construct a tuple is to use the tuple packing feature, which allows you create a tuple from a sequence of comma-separated objects:

py
directions = "North", "South", "East", "West"
print(type(directions))
output
<class 'tuple'>

Accessing Tuple Elements

A tuple item can be referenced by its index. Indexes are integers and start from 0 to n-1 where n is the number of items:

txt
my_tuple = ("a", "b", "c", "d")
             0    1    2    3

In Python indexes are specified with square brackets:

py
my_tuple[index]

For example to access the third element of the tuple, you would use tuple_name[2]:

Terminal
directions = ("North", "South", "East", "West")
directions[2]
output
'East'

If you reference an index that does not exist, an IndexError exception is raised:

output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

To access items in a nested tuple use multiple indexes:

Terminal
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
my_tuple[3][1]
output
'bar'

You can also access the tuple elements using negative indexes. The last item is referred to as -1, the second last item as -2 and so on:

txt
my_tuple = ("a", "b", "c", "d")
            -4   -3   -2   -1
Terminal
directions = ("North", "South", "East", "West")
directions[-2]
output
'East'

Slicing Tuples

In Python, you can slice a tuple and other sequential data types using the following form:

txt
sequence[start:stop:step]
  • start is the index at which the extraction begins. When a negative index is used, it indicates an offset from the end of the tuple. If this argument is omitted, slicing begins from index 0.
  • stop is the index before which to end extraction; the result does not include the “stop” element. When a negative index is used, it indicates an offset from the end of the tuple. If this argument is omitted or greater than the length of the tuple, slicing goes to the end of the tuple.
  • step is an optional argument and specifies the step of the slicing. When not specified, it defaults to 1. If a negative value is used, the slice takes elements in reverse order.

The result of slicing a tuple is a new tuple containing the extracted elements.

The following forms are legal in Python:

py
T[:]            # copy the whole tuple
T[start:]       # from the element at index "start" to the end of the tuple
T[:stop]        # from the beginning up to but not including the element at index "stop"
T[start:stop]   # from index "start" up to but not including index "stop"
T[::step]       # slice the tuple with a stride of "step"

Below is an example of how to slice a tuple starting from the element with index 1 up to but not including the element with index 4:

Terminal
vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]
output
('Garlic', 'Celery', 'Carrots')

Unpacking Tuples

Sequence unpacking is a Python feature that lets you assign the elements of a sequence to variables in a single statement. Here is an example:

py
colors = ('orange', 'white', 'green')
a, b, c = colors
print(a)
print(b)
print(c)

The values of the tuple elements are assigned to the variables on the left according to their position:

output
orange
white
green

When unpacking tuples, the number of variables on the left side must be the same as the number of the tuple elements. Otherwise, you will get a ValueError exception.

py
colors = ('orange', 'white', 'green')
a, b = colors
output
ValueError: too many values to unpack (expected 2)

Unpacking is handy when a method or function returns a sequence of objects:

py
def square_area_perimeter(side_length):
  return side_length * side_length, side_length * 4

area, perimeter = square_area_perimeter(5)

print(area)
print(perimeter)
output
25
20

Changing a Tuple

Since tuples are immutable data structures, we can not update them directly. You can not add, change, or remove elements in tuples.

If you try to change a tuple element you will get a TypeError exception:

py
colors = ("orange", "white", "green")
colors[1] = "blue"
output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Elements of a mutable tuple item can be changed. For example, if the tuple has a list as one of its elements, you can update the list elements:

py
my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)
output
(1, 2, [5, 4, 7])

Concatenating and Repeating Tuples

Even though you can not modify a tuple in place, you can combine tuples with the + operator and repeat them with the * operator. Both operations return a new tuple and leave the originals unchanged:

py
a = (1, 2)
b = (3, 4)
print(a + b)
print(a * 3)
output
(1, 2, 3, 4)
(1, 2, 1, 2, 1, 2)

The first line joins the two tuples into one, and the second repeats the items of a three times.

Tuple Length

The built-in len() function returns the total number of items of a given object.

To find a length of a tuple, pass it as an argument to the len() function:

txt
len(t)

Here is an example:

py
colors = ("orange", "white", "green")
length = len(colors)
print(length)
output
3

Iterating Through a Tuple

To iterate through all elements in a tuple, you can use the for loop:

py
directions = ("North", "South", "East", "West")
for direction in directions:
  print(direction)
output
North
South
East
West

If you need indexes, you have several methods at your disposal. The most common ways are to combine the range() and len() functions or to use the built-in enumerate() function.

The example below shows how to retrieve the index and the value of each item in the tuple:

py
directions = ("North", "South", "East", "West")
for i in range(len(directions)):
  print("Index {} : Value {}".format(i, directions[i]))
output
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West

Instead of using the range(len(...)) pattern, you can use the enumerate() function to loop over a tuple in a more Pythonic way:

py
directions = ("North", "South", "East", "West")
for index, value in enumerate(directions):
  print("Index {} : Value {}".format(index, value))
output
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West

Check if an Element Exists

To check whether an element exists in a tuple, you can use the in and not in operators:

py
colors = ("orange", "white", "green")
print("orange" in colors)

The output will be either True or False:

output
True

Here is another example using the if statement :

py
colors = ("orange", "white", "green")
if "blue" not in colors:
  print("no")
else:
  print("yes")
output
no

Tuple Methods

The tuple object accepts the following methods:

  • count(x) - Returns the number of times ‘x’ appears in the tuple.
  • index(x) - Returns the position of the first occurrence of an element with a value of ‘x’.

Below is a simple example showing how to use the methods:

py
my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))
output
2
0

Tuples vs Lists

Tuples and lists both store ordered collections of items, and most of the time you can use either one. The difference that matters is that a list is mutable and a tuple is immutable, which changes how and when you use each:

FeatureTupleList
Syntaxround brackets ()square brackets []
Mutabilityimmutablemutable
Methodsonly count() and index()many, including append(), insert(), remove()
Typical usefixed records, function returns, dictionary keyscollections that grow or change
Performanceslightly faster, smaller memory footprintmore overhead

Reach for a tuple when the collection should not change after you create it, for example a fixed pair of coordinates or a row returned from a database. Because tuples are immutable and hashable, they can also be used as dictionary keys, which a list can not. Use a list when you need to add, remove, or reorder elements over time.

Named Tuples

When a tuple holds related fields, accessing them by numeric index can become hard to read. The namedtuple() factory from the collections module creates a tuple subclass whose fields also have names:

py
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)

print(p.x)
print(p[1])
output
10
20

A named tuple is still immutable and still works like a regular tuple, so you can index, slice, and unpack it as usual. The named fields make the code clearer when you pass structured data around.

Quick Reference

OperationExampleResult
Createt = (1, 2, 3)tuple with three items
Single elementt = (1,)one-item tuple (comma required)
From an iterabletuple([1, 2])(1, 2)
Accesst[0]first item
Negative indext[-1]last item
Slicet[1:3]items at index 1 and 2
Concatenatet1 + t2combined tuple
Repeatt * 2tuple repeated twice
Lengthlen(t)number of items
Membershipx in tTrue or False
Countt.count(x)times x appears
Indext.index(x)first position of x
Unpacka, b = tassign items to variables

FAQ

What is the difference between a tuple and a list in Python?
A tuple is immutable and written with round brackets (), while a list is mutable and written with square brackets []. Use a tuple for fixed collections and a list when the data needs to change.

How do you create a tuple with one element?
Add a trailing comma, for example t = (1,). Without the comma, (1) is just the integer 1.

How do you convert a list to a tuple?
Pass the list to the tuple() constructor: tuple([1, 2, 3]) returns (1, 2, 3).

Can you change a tuple after creating it?
No. A tuple itself can not be changed, but if it contains a mutable element such as a list, that inner element can still be modified.

Conclusion

Tuples are immutable sequences that are a good fit whenever a collection of values should stay fixed after you create it. For a mutable alternative, see the guide on Python lists , and use enumerate() when you need both the index and the value while looping.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page