Python Tuple



Tuple

A tuple is used to store multiple items in a single variable. It can hold different types (integer, float, string, etc.).

A tuple is a collection that is ordered and unchangeable.

A tuple is one of 4 built-in data types in Python used to store collections of data. The other 3 are List, Set, and Dictionary.


How to create a tuple?

You can create a tuple by placing all items inside parentheses (), separated by commas.

A tuple can have any number of items that can be from different types (integer, float, string, etc.).

# Empty tuple
my_tuple = ()
print(my_tuple)

# tuple of strings
my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")
print(my_tuple)

#  tuple with different datatypes
my_tuple = ("abc", "3", "4.8")
print(my_tuple)


# nested tuple
my_tuple = ("hello", [45, 11, 18], (20, 21, 22))
print(my_tuple)

Output

()
('kiwi', 'apple', 'blueberry', 'dragonfruit')
('abc', '3', '4.8')
('hello', [45, 11, 18], (20, 21, 22))

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1], and so on.


Ordered

In Python, a tuple is ordered. It means that the items inside the tuple have a defined order, and the order will not change.


Unchangeable

In Python, a tuple is unchangeable. It means you cannot change, add, or remove items after the tuple has been created.


Allow Duplicates

Since a tuple is indexed, it can have duplicate values.

In the following example, we will create a tuple with duplicate values.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit", "kiwi")

print(my_tuple)

Output

('kiwi', 'apple', 'blueberry', 'dragonfruit', 'kiwi')

Tuple Length

To determine a length of a tuple, you can use the len() function.

In the following example, we will use the len() function to know how many items our tuple has.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit", "kiwi")

print(len(my_tuple))

Output

5

Create Tuple With One Item

To create a tuple containing only one item, you have to add a comma after the item. If not, Python will not recognize it as a tuple.

In the following example, we will create a one-item tuple.

# Tuple 
my_tuple = ("kiwi",)
print(type(my_tuple))

# Not Tuple
my_tuple = ("kiwi")
print(type(my_tuple))

Output

<class 'tuple'> 
<class 'str'>

Tuple Items - Data Types

Tuple items can be of any data type.

In the following example, we will create three different tuples with different types.

tuple1 = (15, 6, 9, 32, 23)
tuple2 = ("kiwi", "apple", "blueberry")
tuple3 = (True, False, True)

In Python, a tuple can contain different data types.

In the following example, we will create a tuple with integers, strings, and boolean values.

my_tuple = (32, True, "Hello", 16, "Python" )

type()

In Python, tuples are defined as objects with the data type "tuple".

In the following example, we will output the type of a tuple.

my_tuple = ("kiwi", "apple", "blueberry")

print(type(my_tuple))

Output

<class 'tuple'>

The tuple() Constructor

You can also use the tuple() constructor to create a tuple.

In the following example, we will use the tuple() constructor to create a tuple.

# Remember to use the double parentheses
my_tuple = tuple(("kiwi", "apple", "blueberry"))

print(my_tuple)

Output

('kiwi', 'apple', 'blueberry')

Access Tuple Items

There are different ways that you can use to access the items of a tuple.


Tuple Index

Tuple items are indexed, and to access them, you can use the index operator [].

In Python, indices start at 0. For example, a tuple having 5 items will have an index from 0 to 6.

If you try to access indexes other than the allowed interval, an IndexError exception will be raised.

The index of a tuple must be an integer. You can't use float or other types. This will raise a TypeError exception.

my_tuple = ['apple', 'blueberry', 'kiwi', 'orange', 'watermelon', 'mango']

# Output: apple
print(my_tuple[0])

# Output: kiwi
print(my_tuple[2])

# Output: mango
print(my_tuple[5])

## Error. Only integer can be used for indexing
print(my_tuple[2.0])

Output

apple
kiwi
mango

TypeError                                 Traceback (most recent call last)
     11 
     12 ## Error. Only integer can be used for indexing
---> 13 print(my_tuple[2.0])

TypeError: list indices must be integers or slices, not float

To access nested tuple, you can use nested indexing.

# nested tuple
my_tuple = ("hello", [45, 11, 18], (20, 21, 22))

# nested index
print(my_tuple[0][3])
print(my_tuple[2][2])

Output

e 
22

Negative Indexing

Python allows negative indexing for its sequences.

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

Let us see the following example:

my_tuple = ('w', 'o', 'r', 'l', 'd')

# Output: d
print(my_tuple[-1])

# Output: r
print(my_tuple[-3])

Output

d
r

The following illustration shows the index and the negative of a tuple:

Tuple indexing in Python

How to slice a tuple in Python?

You can specify a range of indexes by indicating where a range starts and ends using the slicing operator : (colon).

The return value of a specified range will be a new tuple with the designated items.

Let us see the following examples:

fruits = ("kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes")

# items 'th to 5th
print(fruits([3:5))

# items 5th to end
print(fruits([4:))

# items beginning to end
print(fruits([:))

Output

('dragonfruit', 'banana')
('banana', 'peach', 'mango', 'grapes')
('kiwi', 'apple', 'blueberry', 'dragonfruit', 'banana', 'peach', 'mango', 'grapes')

Note: Remember when using the range of index that the start is included but not the end.


Slicing using a Range of Negative Indexes

You can use negative indexes if you want to start the search from the end of the list.

In the following example, we will return the items from "dragonfruit" (-5 index) to "mango" (-2 index) but without including the last one.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes"]

print(fruits[-6:-1])

Output

['blueberry', 'dragonfruit', 'banana', 'peach', 'mango']

Check if Item Exists in a tuple

You can check if an item is present in a tuple using the in keyword.

In the following example, we will check if "mango" is present in the "fruits" tuple.

fruits = ("kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes")

if "mango" in fruits:
    print("Yes, 'mango' is on the fruits tuple")

Output

Yes, 'mango' is on the fruits tuple

Update Tuples

In Python, tuples are unchangeable, meaning you cannot add, change, or remove items once a tuple is created.

But you can use some workarounds to change tuples.


Change Tuple Values

Tuples are unchangeable, or immutable.

Once a tuple is created, you cannot change its values.

But you can use a workaround. You can convert a tuple into a list, change the list, and convert the list back into a tuple.

In the following example, we will convert a tuple into a list, change the list, and convert it back into a tuple.

a = ("kiwi", "apple", "blueberry", "dragonfruit")
b = list(a)
b[2] = "orange"

a = tuple(b)
print(a)

Output

('kiwi', 'apple', 'orange', 'dragonfruit')

Add Items

Once a tuple is created, you cannot add items to it.

But you can use the same workaround for changing a tuple. You can convert the tuple into a list, add your items, and convert it back into a tuple.

In the following example, we will convert the tuple into a list, add the "strawberries" item, and convert it back into a tuple.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

my_list = list(my_tuple)
my_list.append("strawberries") 

my_tuple = tuple(my_list)
print(my_tuple)

Output

('kiwi', 'apple', 'blueberry', 'dragonfruit', 'strawberries')

Remove Items

Once a tuple is created, you cannot remove items from it.

But you can use the same workaround for changing and adding tuple items. You can convert the tuple into a list, remove your items, and convert it back into a tuple.

In the following example, we will convert the tuple into a list, remove the "dragonfruit" item, and convert it back into a tuple.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

my_list = list(my_tuple)
my_list.remove("dragonfruit")

my_tuple = tuple(my_list)
print(my_tuple)

Output

('kiwi', 'apple', 'blueberry')

You can also delete the tuple completely using the keyword del.

In the following example, we will use the del keyword to delete the tuple.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

del my_tuple

# It will raise an error 
print(my_tuple)

Output

NameError                                 Traceback (most recent call last)

----> 6 print(my_tuple)
NameError: name 'my_tuple' is not defined

Unpack Tuples

There is a powerful tuple assignment feature in Python that assigns the right-hand side of values into the left-hand side. It is named unpacking of a tuple of values into a variable.

The opposite of unpacking is packing. In packing, we put values into a new tuple, while in unpacking, we extract tuple values into a single variable.


Unpacking a Tuple

When you create a tuple, you assign values to it. This is called "packing" a tuple.

In the following example, we will pack a tuple.

# packing a tuple
my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

print(my_tuple)

Output

('kiwi', 'apple', 'blueberry', 'dragonfruit')

Python also offers the possibility to extract the values back into variables. This is called "unpacking".

In the following example, we will unpack a tuple.

my_tuple = ("kiwi", "potatoes", "coca")

# unpack a tuple
(fruit, vegetable, liquid) = my_tuple

print(fruit)
print(vegetable)
print(liquid)

Output

kiwi
potatoes
coca

Note: When unpacking, the number of variables must match the number of values in the tuple. If not, you must use an asterisk to collect the remaining values as a list.


Unpacking a Tuple using Asterisk *

When unpacking, if the number of variables is less than the number of values in the tuple, you can add an asterisk * to the variable name, and the values will be assigned to the variable as a list.

In the following example, we will assign the rest of the values as a list called "other_fruits".

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

(kiwi_fruit, *other_fruits) = my_tuple

print(kiwi_fruit)
print(other_fruits)

Output

kiwi 
['apple', 'blueberry', 'dragonfruit']

If the asterisk is added to another variable name than the last, Python will assign to the variable until the number of values left matches the number of variables left.

In the following example, we will add the asterisk to the "other_fruits".

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit", "strawberry")

(kiwi_fruit, *other_fruits, strawberry_fruit) = my_tuple

print(kiwi_fruit)
print(other_fruits)
print(strawberry_fruit)

Output

kiwi 
['apple', 'blueberry', 'dragonfruit'] 
strawberry

Loop Tuples

There are different ways to loop through tuples.


Loop through a Tuple using a For Loop

You can loop through the tuple items by using a for loo.

In the following example, we will iterate through tuple items and print the values.

v

Output

kiwi
apple
blueberry
dragonfruit

Loop Through the Index Numbers

You can also loop through the tuple items by referring to their index number.

You can use the range() and len() functions to create a suitable iterable.

In the following example, we will print all items by referring to their index number.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

for i in range(len(my_tuple)):
    print(my_tuple[i])

Output

kiwi
apple
blueberry
dragonfruit

Loop through a Tuple using a While Loop

It is possible to loop through the tuple items using a while loop.

We will use the len() method to determine the length of the tuple. We will start at the 0 indexes and loop through the tuple items by referring to their indexes.

In the following example, we will print all the tuple items using the while loop.

my_tuple = ("kiwi", "apple", "blueberry", "dragonfruit")

size = len(my_tuple)
i = 0

while i < size:
    print(my_tuple[i])
    i = i +1

Output

kiwi
apple
blueberry
dragonfruit

Join Tuples

Join Two Tuples

You can join two or more tuples using the + operator.

In the following example, we will join two tuples.

tuple1 = ("apple", "kiwi", "orange")
tuple2 = ("a", "b", "c")

tuple3 = tuple1 + tuple2

print(tuple3)

Output

('apple', 'kiwi', 'orange', 'a', 'b', 'c')

Multiply Tuples

If you want to multiply the content of a tuple a given number of times, you can use the asterisk * operator.

In the following example, we will multiply the "my_tuple" by 2.

my_tuple = ("apple", "kiwi", "orange")
my_tuple = my_tuple * 2

print(my_tuple)

Output

('apple', 'kiwi', 'orange', 'apple', 'kiwi', 'orange')

Tuple Methods

Python offers two built-in methods that you can use on tuples.

Method Description
count() It is used to return the number of times a specified value occurs in a tuple.
index() It is used to search in the tuple for a specified value and returns the position of where it was found

When to use Tuple over List?

Tuples are similar to lists, and both of them are used in similar situations. However, there are some advantages of using a tuple over a list.

In the following list, we will see when to use a tuple over a list.

  • In general, tuples are used when using different data types and lists when using similar data types.
  • Tuples are immutable, so iterating through a tuple is faster than with a list.
  • Tuples that contain immutable items can be used as a key for a dictionary. This is impossible using a list.
  • If you are using immutable data (data that doesn't change), implementing it as a tuple will guarantee that it remains unchangeable.


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.