11.Tuples In Python

What is Tuples?

Tuples are used to store multiple items in a single variable. It is also an iterable.

In more simpler terms, Tuple is a collection of items enclosed between Parantheses ().

Properties : Ordered , immutable(unchangeable) , Allow Duplicate Values.

For Example:

In [1]:

name = ('Mark','Bill','Elon')
print(name)

Memory Allocation of Tuple items:

As we know that Tuples is a sequence of items, hence Each item of Tuple gets store in different memory block, similar to list.

Indexing and Slicing in Tuple:

Indexing and Slicing in Tuple is also similar to list. For Example:

In [2]:

#indexing in Tuple:
name = ('Mark','Bill','Elon')
name[1]

In [3]:

In [4]:

Properties of a Tuple:

1.Tuples are Ordered:

When You define a Tuple , its items are stored and assigned to specific index number. It means Tuple items are ordered . To Explain it better, Here is an Example:

In [7]:

1.Tuples are Immutable/UnChangeable:

We cannot change the items in Tuple once defined.

In [8]:

3.Tuples allow duplicate values:

Tuple allows duplicate values, it can have as many duplicate values. For Example:

In [9]:

Functions used in Tuple :

len() function:

len() function is used to count items in a Tuple. For Example:

In [10]:

max() function:

max() function is used to return largest value or item in a Tuple ,For Example:

In [11]:

In [12]:

max() and min() function does not work in mixed Tuples with different category of data types , Just like Lists.

Tuple Operations:

how to Concatenate two Tuples ++:

Repetition of two Tuples :

Membership operator in Tuples:

iteration in tuples:

for loop is used to iterate over the Tuple items. For example:

Empty Tuple:

We can create an empty tuple with the help of parantheses ().

To create a tuple with Single item:

In tuple , You can not simply create a tuple with single item. For example:

Now , here var is not a tuple , it is an integer because python treats parantheses here as Operator. So What is the Solution?

So , We can create a tuple with single item by using comma like above.

Tuple Methods:

Since We cannot change values in Tuple once we have defined tuple. So there are only two methods in Tuple.

1.count() :

count method is used to count occurence of elements in Tuples.

2.index() :

index method is used to find position of element in tuple.

tuple() Constructor :

tuple constructor is used to convert an iterable to tuple. We can also use to create an empty tuple with it.

Last updated