tuples in Python

Published: May 10, 2022

tuples in Python

In this article, we would cover tuples in Python. Just like lists, it is a sequence data type. In a sequence, an index number or sequence is assigned to each element. The index number starts with zero. Therefore, element at first index is assigned zero, element at second index is assigned one and so on till the end of sequence.

tuples in Python

A tuple can store multiple elements in single sequence. So, in a way these are pretty similar to lists. But, there is a catch - these are immutable sequences. That means, we can't change the contents of a tuple. Whereas, we can change the contents of a list.

Generally, we write tuples in parentheses and commas separate the elements of a tuple. Let's understand it with the help of an example -

tupex = ("book", "science", 9)

To check whether the above is a tuple or not -

type(tupex)

This would return with -

<class 'tuple'>

Next, we turn our attention to couple of operations which we can perform on tuples. First, to find the length of a tuple, we use len() method. Continuing with the above example -

print(len(tupex))

It would return with -

3

To get a particular element by providing the index number. Let's say we want to fetch the element at index 1 -

tupex[1]

This would return with -

'science'

We would like to reiterate here that, once a tuple is created we can't modify it. Reason - these are immutable sequences. Apart from that, we have a tuple() method. It is a built-in function which is used to take sequence as an input and convert it into a tuple. Let's say we have a list, x -

x=[23, "apple", 165]

To convert it into a tuple -

y = tuple(x)

To get what's stored in y -

y

It would return with -

(23, 'apple', 165)

To verify whether things worked as we desire, check for the sequence type -

type(x)

It should return with -

<class 'list'>

and, for y -

type(y)

The output would be -

<class 'tuple'>

In conclusion, we have discussed tuples in Python here. Although, there wasn't much of detail but definitely provides an overview of how things work.