Python Tuple

Python Tuple

In Python, Tuple is a collection of items. In Python Tuple, items are ordered, and therefore can be accessed using index.

Also, an important property to note about Python Tuple is that, it is immutable. You cannot change the items of a tuple in Python.

But, if it is really necessary for you to change a tuple, you may convert the tuple to a list, modify it, and convert back to a list. This is only a workaround to modify a tuple.

Examples for Python Tuple

In Python, a tuple is defined using parenthesis. The elements are defined inside parenthesis and are comma separated.

A Python Tuple can contain a definite number of items belonging to different datatypes.

Following are some of the examples for Tuples in Python.

tuple1 = (14, 52, 17, 24)
tuple2 = ('Hello', 'Hi', 'Good Morning')
tuple3 = (1, 'Tony', 25)
Run this program

Access Tuple Items using Index

As Tuple items are ordered, you can access them using index as that of items in a Python List.

Python Program

tuple1 = (14, 52, 17, 24)
print(tuple1[1])
print(tuple1[3])
Run this program

Output

52
24

Python Tuple Length

Like any other collection in Python, you may use len() builtin function to get the length of a tuple.

Python Program

tuple1 = (14, 52, 17, 24)
print( len(tuple1) )
Run this program

Output

4

Iterate over items of Python Tuple

You can iterate over Python Tuple’s items using for loop.

Python Program

tuple1 = (14, 52, 17, 24)
for item in tuple1:
    print(item)
Run this program

Output

14
52
17
24

Or you can also use while loop with tuple length and index to iterate over tuple’s items.

Python Program

tuple1 = (14, 52, 17, 24)

index = 0
while index<len(tuple1):
    print(tuple1[index])
    index = index + 1
Run this program

Output

14
52
17
24

Summary

In this Python Tutorial, we learned what a Tuple is in Python and how to define and access it in different ways.