Python Tuples: Create, Access, Slice, and Unpack

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:
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 :
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))Round brackets with no elements in between them denote an empty tuple:
my_tuple = ()To create a tuple with only one element you must add a comma after the element:
my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)<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:
colors_list = ['orange', 'white', 'green']
colors_tuple = tuple(colors_list)
print(type(colors_tuple))<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:
directions = "North", "South", "East", "West"
print(type(directions))<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:
my_tuple = ("a", "b", "c", "d")
0 1 2 3In Python indexes are specified with square brackets:
my_tuple[index]For example to access the third element of the tuple, you would use tuple_name[2]:
directions = ("North", "South", "East", "West")
directions[2]'East'If you reference an index that does not exist, an IndexError exception is raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of rangeTo access items in a nested tuple use multiple indexes:
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
my_tuple[3][1]'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:
my_tuple = ("a", "b", "c", "d")
-4 -3 -2 -1directions = ("North", "South", "East", "West")
directions[-2]'East'Slicing Tuples
In Python, you can slice a tuple and other sequential data types using the following form:
sequence[start:stop:step]startis 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.stopis 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.stepis 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:
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:
vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]('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:
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:
orange
white
greenWhen 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.
colors = ('orange', 'white', 'green')
a, b = colorsValueError: too many values to unpack (expected 2)Unpacking is handy when a method or function returns a sequence of objects:
def square_area_perimeter(side_length):
return side_length * side_length, side_length * 4
area, perimeter = square_area_perimeter(5)
print(area)
print(perimeter)25
20Changing 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:
colors = ("orange", "white", "green")
colors[1] = "blue"Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignmentElements 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:
my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)(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:
a = (1, 2)
b = (3, 4)
print(a + b)
print(a * 3)(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:
len(t)Here is an example:
colors = ("orange", "white", "green")
length = len(colors)
print(length)3Iterating Through a Tuple
To iterate through all elements in a tuple, you can use the for
loop:
directions = ("North", "South", "East", "West")
for direction in directions:
print(direction)North
South
East
WestIf 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:
directions = ("North", "South", "East", "West")
for i in range(len(directions)):
print("Index {} : Value {}".format(i, directions[i]))Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value WestInstead of using the range(len(...)) pattern, you can use the enumerate() function to loop over a tuple in a more Pythonic way:
directions = ("North", "South", "East", "West")
for index, value in enumerate(directions):
print("Index {} : Value {}".format(index, value))Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value WestCheck if an Element Exists
To check whether an element exists in a tuple, you can use the in and not in operators:
colors = ("orange", "white", "green")
print("orange" in colors)The output will be either True or False:
TrueHere is another example using the if statement
:
colors = ("orange", "white", "green")
if "blue" not in colors:
print("no")
else:
print("yes")noTuple 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:
my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))2
0Tuples 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:
| Feature | Tuple | List |
|---|---|---|
| Syntax | round brackets () | square brackets [] |
| Mutability | immutable | mutable |
| Methods | only count() and index() | many, including append(), insert(), remove() |
| Typical use | fixed records, function returns, dictionary keys | collections that grow or change |
| Performance | slightly faster, smaller memory footprint | more 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:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x)
print(p[1])10
20A 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
| Operation | Example | Result |
|---|---|---|
| Create | t = (1, 2, 3) | tuple with three items |
| Single element | t = (1,) | one-item tuple (comma required) |
| From an iterable | tuple([1, 2]) | (1, 2) |
| Access | t[0] | first item |
| Negative index | t[-1] | last item |
| Slice | t[1:3] | items at index 1 and 2 |
| Concatenate | t1 + t2 | combined tuple |
| Repeat | t * 2 | tuple repeated twice |
| Length | len(t) | number of items |
| Membership | x in t | True or False |
| Count | t.count(x) | times x appears |
| Index | t.index(x) | first position of x |
| Unpack | a, b = t | assign 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 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