Python Tuples - Introduction


What is a Tuple in Python?

In Python, Tuple is a collection of items where the items are ordered.

Since the items are ordered, they 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.

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. But, by design, tuple cannot be modified.

Tuple Examples

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)

Create a tuple in Python

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'])

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])

Output

52
24

Finding tuple length in Python

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) )

Output

4

Iterating over items of tuple in Python

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

Python Program

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

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

Output

14
52
17
24

Tuple Concepts

Tuple Operations

Tuple Methods

There are two method defined for tuple objects. They are

Summary

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