Python Tuple

A Tuple is the collection of immutable Python objects. Tuples are sequences, just like lists.  But, the main difference between list and tuple is, Tuple is immutable means it isn’t allowed to change value. A tuple is written in round brackets. An index number is used to access a particular Tuple element like List.

Create Tuple

>>> vehicle = ('car','truck','bus')
>>> vehicle
('car', 'truck', 'bus')

Access Tuple Element

You can access the tuple element by index same as like list and string. You can also access the range of tuple elements by defining the first and last index in [start : end] brackets separated by a colon. Here, the end is exclusive.

>>> vehicle[1]
truck

>>> vehicle[-2]
truck

>>> vehicle[:2]
('car', 'truck')
>>> vehicle[-3:-1]
('car', 'truck')

Add, Update and Remove Element: 

A tuple is immutable, so you are not allowed to add or change the tuple elements once it is created. Removing the individual element from tuple is also not allowed, but you can remove the entire tuple by del keyword.

>>> vehicle = ('car','truck','bus')
>>> del vehicle             # It will delete the entire tuple.

.     .     .

Python provides the various built-in functions for a tuple operation. This tutorial has explained it with examples.

>>> vehicle = ('car','truck','bus')
>>> len(vehicle)                   # return total number of elements in a tuple
3

>>> t1 = (1,2,3)
>>> t2 = (10,20,30)
>>> t1+t2                      # Join two tuple
(1,2,3,10,20,30)

>>> max(t2)                    # Returns item from the tuple with max value.
30

>>> min(t2)                    # Returns item from the tuple with min value.
10

Convert Tuple to List – Python’s list(t1) function is used to convert a tuple t1 to list.

>>> t1 = (1,2,3,4,5,6,7,8,9,10)
>>> list(t1)
[1,2,3,4,5,6,7,8,9,10]

Convert List to Tuple – tuple(li) method used to convert list li to the tuple.

>>> li = [1,2,3,4,5,6,7,8,9,10]
>>> tuple(li)
(1,2,3,4,5,6,7,8,9,10)

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials