Google News
logo
Python Tuples
A tuple is a sequence of immutable Python objects.  

The objects are enclosed within parenthesis and separated by comma. Optionally you can put these comma-separated values between parentheses also. 

Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
>>> data=(10,20,'Ramana',63.8)
>>> data2="a",10,20.9
>>> data
(10, 20, 'Ramana', 63.8)
>>> data2
('a', 10, 20.9)
>>> 
The empty tuple is written as two parentheses containing nothing :
tup1 = ();
For a single valued tuple, there must be a comma at the end of the value.
tup1 = (54,);
>>> tuple_1='a','Ramana',36.18
>>> tuple_2=tuple_1,(9,18,27)
>>> print(tuple_1)
('a', 'Ramana', 36.18)
>>> print(tuple_2)
(('a', 'Ramana', 36.18), (9, 18, 27))
>>> 

Accessing Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.

>>> tuple_1 = ('Python', 'PHP', 39, 55);
>>> tuple_2 = (1, 2, 3, 4, 5, 6, 7 );
>>> print (tuple_1[0])
Python
>>> print (tuple_2[1:5])
(2, 3, 4, 5)
>>> 

Changing a Tuple

Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.

>>> my_tuple = (1, 4, 2, 3, 6, [7, 5])
>>> my_tuple[5][0] = 8
>>> print(my_tuple)
(1, 4, 2, 3, 6, [8, 5])
>>> my_tuple = ('f','r','e','e','t','i','m','e','l','e','a','r','n')
>>> print(my_tuple)
('f', 'r', 'e', 'e', 't', 'i', 'm', 'e', 'l', 'e', 'a', 'r', 'n')
>>> 

We can use + operator to combine two tuples. This is also called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result into a new tuple.

>>> # Concatenation
>>> # Output: (1, 2, 3, 4, 5, 6)
>>> print((1, 2, 3) + (4, 5, 6))
(1, 2, 3, 4, 5, 6)
>>> # Repeat
>>> # Output: ('Repeat', 'Repeat', 'Repeat')
>>> print(("Repeat",) * 3)
('Repeat', 'Repeat', 'Repeat')
>>> 

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.

But deleting a tuple entirely is possible using the keyword del.

>>> my_tuple = ('f','r','e','e','t','i','m','e','l','e','a','r','n')
>>> del my_tuple
>>> print(my_tuple)
Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    print(my_tuple)
NameError: name 'my_tuple' is not defined
>>> 

Tuple Functions

here are following in-built Type Functions :

Function Description
min(tuple) Returns the minimum value from a tuple.
max(tuple) Returns the maximum value from the tuple.
len(tuple) Gives the length of a tuple
cmp(tuple1,tuple2) Compares the two Tuples.
tuple(sequence) Converts the sequence into tuple.