Python Tuple Operations

Python Tuple Operations

Python Tuple is an immutable collection of items. Also, tuple is an ordered collection. These properties of a tuple enable some operations like accessing the items using an index, iterating over its elements, etc., and disable some of the operations like updating tuple items.

In this tutorial, we will go through some of the commonly tuple operations in Python programming.

Create a Tuple

To create a tuple, you can provide the comma separated items enclosed in parenthesis or use tuple() builtin function. tuple() accepts an iterable and converts the iterable into tuple.

In the following program, we will create a tuple in two ways: using parenthesis and tuple() builtin function.

Python Program

tuple1 = ('a', 'e', 'i', 'o', 'u')
tuple2 = tuple(['a', 'e', 'i', 'o', 'u'])
Run this program

Access Tuple Items

Tuple is an ordered collection. So, you can access its items using index, just like a Python List.

Python Program

tupleX = ('a', 'e', 'i', 'o', 'u')
print(tupleX[0])
print(tupleX[1])
print(tupleX[2])
print(tupleX[3])
print(tupleX[4])
Run this program

Output

a
e
i
o
u

The index starts at 0 for the first item, and increments for the subsequent items.

You can also use negative indexing. To learn more about accessing items of tuple, refer Python Access Tuple.

Iterate over Tuple Items

Tuple returns an iterator, and you can use for loop to iterate over the items. Or using the index and while loop, you can iterate over tuple items.

Python Program

tupleX = ('a', 'e', 'i', 'o', 'u')
for item in tupleX:
	print(item)

tupleY = (5, 6, 3, 2)
index = 0
while index < len(tupleY):
	print(tupleY[index])
	index += 1
Run this program

Output

a
e
i
o
u
5
6
3
2

List of all Tuple Operations

Following are the list of tuple operations that we can perform in Python. Each of these tutorial provide well detailed examples to understand each operation.

Summary

In this tutorial of Python Examples, we learned how to use Tuple in a Python program with different usages of tuple presented as examples and tutorials.