Skip to main content

Python Tuple

Python Tuple is an ordered sequence of immutable items.

Tuples are similar to lists, but once created the elements of a tuple can't be changed (tuples are immutable).

Create Python Tuples

A tuple is defined by listing the elements in round brackets ( ), separated by commas.

note

Parentheses are optional, however, it is good practice to use them because they make the tuple easily recognizable.

A tuple can have any number of elements and can be of different types (integer, float, list, string, etc.).

Let's look at the different types of tuples:

# Empty tuple
my_tuple = ()
print(my_tuple) # ()

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple) # (1, 2, 3)

# tuple with mixed datatypes
my_tuple = (1, "a string", 2.3)
print(my_tuple) # (1, 'a string', 2.3)

# nested tuple
my_tuple = ("a string", [8, 4, 6], (1, 2, 3))
print(my_tuple) # ('a string', [8, 4, 6], (1, 2, 3))

A tuple can also be created without using parentheses. This operation is known as tuple packing.

my_tuple = 1, 2.3, "a string"
print(my_tuple)

# tuple unpacking is also possible
a, b, c = my_tuple

print(a) # 1
print(b) # 2.3
print(c) # a string

Creating a tuple with a single element is a bit tricky, because it is not enough to have an element in parentheses: a final comma must be added to indicate that it is a tuple with a single element.

my_tuple = ("a string")
print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element
my_tuple = ("a string",)
print(type(my_tuple)) # <class 'tuple'>

# Parentheses is optional
my_tuple = "a string",
print(type(my_tuple)) # <class 'tuple'>

Access Tuple Elements

There are several ways to access items in a tuple.

with Index

The index operator [] can be used to access an item in a tuple.

  • In Python, the tuple index starts from 0.
  • The index must be an integer. Using values of any other type will result in a TypeError.
  • Nested tuples are accessed using nested indexing.
warning

If you attempt to access elements outside the index bounds, an IndexError is generated.

Tuple Examples
my_tuple = ('t','u','t','o','r','i','a','l')

print(my_tuple[0]) # 't'
print(my_tuple[5]) # 'i'

# IndexError: tuple index out of range
# print(my_tuple[6])

# Index must be an integer
# TypeError: tuple indices must be integers or slices, not float
# my_tuple[2.0]
Nested Tuple Example
# nested tuple
n_tuple = ("a string", [4, 5, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 't'
print(n_tuple[1][1]) # 5

with Negative Index

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

my_tuple = ('t', 'u', 't', 'o', 'r', 'i', 'a', 'l')

# last item
print(my_tuple[-1]) # l

# fifth last item
print(my_tuple[-4]) # r

Slicing

A range of elements in a tuple can be accessed using the slicing operator :.

note

In [from:to] syntax, the initial index is inclusive but the final index is exclusive.

The possible cases (with examples) are shown in the table below:

SliceDescriptionExample with li=(10,20,30,40)
my_tuple[from:to]the elements from from to to-1li[1:3] -> (20,30)
my_tuple[from:]the elements from from to the end of the tupleli[2:] -> (30,40)
my_tuple[:to]the elements from the beginning of the tuple to the element to-1li[:3] -> (10,20,30)
my_tuple[:]all elementsli[:] -> (10,20,30,40)
my_tuple[from:to:step]one element each step from from to to-1li[0:3:2] -> (10,30)
my_tuple[from::step]one item each step from from until the end of the tupleli[1::2] -> (20,40)
my_tuple[:to:step]one element each step from the beginning to the to-1 element.li[:3:2] -> (10,30)
my_tuple[::step]one item each stepli[::2] -> (10,30)

Tuple Manipulation

Tuples are immutable, i.e, elements of a tuple can't be modified once assigned.

note

However, if the element is a mutable data type, such as a list, its nested elements can be modified.

Change a Tuple

If the element of a tuple is a mutable data type, such as a list, its nested elements can be modified.

# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9

# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)

Tuples can be reassigned to different values (reassignment).

my_tuple = ('t','u','t','o','r','i','a','l')
print(my_tuple) # ('t','u','t','o','r','i','a','l')
my_tuple = (1,2,3, [4,5] ) # reassign
print(my_tuple) # (1,2,3,4,5)

Concatenation an Repetition

The + operator is used to combine two tuples. This is called concatenation.

Using the * operator, elements of a tuple can be repeated a specific number of times to create a new tuple.

note

Both + and * operators result in a new tuple.

# Concatenation
print((1, 2, 3) + (4, 5, 6)) # (1, 2, 3, 4, 5, 6)

# Repeat
print(("TutRef",) * 3) # ('TutRef', 'TutRef', 'TutRef')

Delete a Tuple

As mentioned above, it is not possible to modify the elements of a tuple.

However, it is possible to completely delete a tuple using the del statement

my_tuple = (0, 1, 2, 3, 4, 5)

# can't delete single items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]

# Can delete an entire tuple
del my_tuple

# NameError: name 'my_tuple' is not defined
print(my_tuple)

Other Tuple Operations

Tuple Membership Test

The keyword in is used to check whether an item exists in a tuple.

my_tuple = ['t','u','t','o','r','i','a','l']

print('t' in my_tuple) # True
print('e' in my_tuple) # False
print('c' not in my_tuple) # True

Iterating Through a Tuple

Using a for loop, it is possible to iterate each element of a tuple.

for color in ('red','blue','yellow'):
print("I'm wearing a", color, "t-shirt")

Output

I'm wearing a red t-shirt
I'm wearing a blue t-shirt
I'm wearing a yellow t-shirt
note

See Python For Loop to learn more.

Summary of Python Tuple Methods

MethodDescription
count()returns the count of the number of items passed as an argument
index()returns the index of the first matched item
my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3