Learn Python Programming

Python Tuple

A tuple is a python sequence which stores multiple elements or a group of elements in a single variable. A tuple elements is ordered and immutable. Tuple is unchangeable it means once the tuples are created, it’s element can not be modified. Tuples are generally used to store data which should not be modified and only retrieve those data on demand.

  • Tuples are ordered. It means each element in tuple have defined order and that order will not be changed.
  • Tuples are immutable (unchangeable).
  • Tuples are written with round brackets ().
  • The elements inside tuples can be of same datatype or different datatypes.
  • Tuple allow duplicate elements.
  • In tuples, append(), extend(), insert(), remove(), pop() and clear() operations are not preformed as values are unchangeable in tuples.

Creating Tuples

Tuples are created by writing elements by comma separated and enclosed within parenthesis ().

#Empty Tuples
tuple1 = ()

#Tuple with single element inside, comman(,) is compulsory after element
tuple1 = (10,)

#Tuple with different types of elements
tuple1 = (10, 20, -32, 30.5, "Delhi", "Patna")

#Tuple can have only one datatype elements
tuple2 = (2, 49, 22, 39, 10)      #tuple with integers

If we do not mention any brackets and write elements by comma separated, then by default it is considered as a tuple.

tuple_3 = 2, 49, 22, 39, 10 

A list can also be converted into tuple by tuple() function.

list_sequence = [1,2,3,4,5]
tuple_sequence = tuple(list_sequence)

(1, 2, 3, 4, 5)

A tuple can be created by using range() function.

tuple_sequence = tuple(range(1,10,1))

(1, 2, 3, 4, 5, 6, 7, 8, 9)

Accessing the Tuple Elements

Tuple elements can be accessed by using the indexing and slicing. This is the same methods like list.

tuple_sequence = (10, 20, 30, 40, 50, 60)

#negative indexing

#negative indexing

(60, 40, 20)
(50, 40, 30, 20, 10)

Functions to process tuples

There are some important functions and methods available in python which can directly operates with function or method name. Index() and count() are not functions, they are methods. So these two methods are used in format, Object.method().

len()len(tpl)Returns the number of elements in the tuple.
min()min(tpl)Returns the smallest element in the tuple.
max()max(tpl)Returns the greatest element in the tuple.
count()tpl.count(x)Returns how many times the specified element ‘x’ is available in tuple.
index()tpl.index(x)Returns the first occurrence of the element ‘x’ in tuple tpl.
sorted()sorted(tpl)Returns the sorted tuple tpl in ascending order. Sorted(tpl, reverse=True) will sort tuple tpl in descending order.