Python - Tuples

Tuple is an immutable (unchangeable) collection of elements of different data types. It is an ordered collection, so it preserves the order of elements in which they were defined.

Tuples are defined by enclosing elements in parentheses (), separated by a comma. The following declares a tuple type variable.

Example: Tuple Variable Declaration
tpl=() # empty tuple
print(tpl)

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple
print(names)

nums = (1, 2, 3, 4, 5) # int tuple
print(nums)

employee=(1, 'Steve', True, 25, 12000)  # heterogeneous data tuple
print(employee)
Output:
()
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000)

However, it is not necessary to enclose the tuple elements in parentheses. The tuple object can include elements separated by a comma without parentheses.

Example: Tuple Variable Declaration
names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple
print(names)

nums = 1, 2, 3, 4, 5 # int tuple
print(nums)

employee=1, 'Steve', True, 25, 12000  # heterogeneous data tuple
print(employee)
Output:
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000)

Tuples cannot be declared with a single element unless followed by a comma.

Example: Tuple Variable Declaration
names = ('Jeff') # considered as string type
print(names)
print(type(names))

names = ('Jeff',) # tuple with single element
print(names)
print(type(names))
Output:
'Jeff'
<class 'string'>
(Jeff)
<class 'tuple'>

Access Tuple Elements

Each element in the tuple is accessed by the index in the square brackets []. An index starts with zero and ends with (number of elements - 1), as shown below.

Example: Access Tuple Elements using Indexes
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[0]) # prints 'Jeff'
print(names[1]) # prints 'Bill'
print(names[2]) # prints 'Steve'
print(names[3]) # prints 'Yash'

nums = (1, 2, 3, 4, 5) 
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5
Output:
Jeff
Bill
Steve
Yash
1
2
5

The tuple supports negative indexing also, the same as list type. The negative index for the first element starts from -number of elements and ends with -1 for the last element.

Example: Negative Indexing
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash'
Output:
Jeff
Bill
Steve
Yash

If the element at the specified index does not exist, then the error "index out of range" will be thrown.

>>> names[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Tuple elements can be unpacked and assigned to variables, as shown below. However, the number of variables must match with the number of elements in a tuple; otherwise, an error will be thrown.

Example: Access Tuple Elements using Indexes
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
a, b, c, d = names # unpack tuple
print(a, b, c, d)
Output:
Jeff Bill Steve Yash

Update or Delete Tuple Elements

Tuple is unchangeable. So, once a tuple is created, any operation that seeks to change its contents is not allowed. For instance, trying to modify or delete an element of names tuple will result in an error.

>>> names = ('Jeff', 'Bill', 'Steve', 'Yash') 
>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del names[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

However, you can delete an entire tuple using the del keyword.

>>> del names

Tuple Class

The underlying type of a tuple is the tuple class. Check the type of a variable using the type() function.

Example: Tuple Variable Declaration
names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print('names type: ', type(names))

nums = (1,2,3,4,5) 
print('nums type: ', type(nums))
Output:
names type: <class 'tuple'>
nums type: <class 'tuple'>

The tuple() constructor is used to convert any iterable to tuple type.

Example: Tuple Variable Declaration
tpl = tupe('Hello') # converts string to tuple
print(tpl)
tpl = tupe([1,2,3,4,5]) # converts list to tuple
print(tpl)
tpl = tupe({1,2,3,4,5}) # converts set to tuple
print(tpl)
tpl = tuple({1:"One",2:"Two"}) # converts dictionary to tuple
print(tpl)
Output:
('H','e','l','l','o')
(1,2,3,4,5)
(1,2,3,4,5)
(1,2)

Tuple Operations

Like string, tuple objects are also a sequence. Hence, the operators used with strings are also available for the tuple.

Operator Example
The + operator returns a tuple containing all the elements of the first and the second tuple object.
>>> t1=(1,2,3)
>>> t2=(4,5,6)         
>>> t1+t2              
(1, 2, 3, 4, 5, 6) 
>>> t2+(7,)            
(4, 5, 6, 7)
The * operator Concatenates multiple copies of the same tuple.
>>> t1=(1,2,3)
>>> t1*4                             
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given index. A negative index counts the position from the right side.
>>> t1=(1,2,3,4,5,6)     
>>> t1[3]                
4                        
>>> t1[-2]               
5
The [:] operator returns the items in the range specified by two index operands separated by the : symbol.
If the first operand is omitted, the range starts from zero. If the second operand is omitted, the range goes up to the end of the tuple.
>>> t1=(1,2,3,4,5,6) 
>>> t1[1:3]              
(2, 3)                   
>>> t1[3:]               
(4, 5, 6)                
>>> t1[:3]               
(1, 2, 3)
The in operator returns true if an item exists in the given tuple.
>>> t1=(1,2,3,4,5,6) 
>>> 5 in t1
True                
>>> 10 in t1 
False
The not in operator returns true if an item does not exist in the given tuple.
>>> t1=(1,2,3,4,5,6) 
>>> 4 not in t1 
False                    
>>> 10 not in t1
True

Built-in Tuple Methods

len()

Returns the number of elements in the tuple.

>>> t1=(12,45,43,8,35)
>>> len(t1)
5

max()

If the tuple contains numbers, the heighest number will be returned. If the tuple contains strings, the one that comes last in alphabetical order will be returned.

>>> t1=(12, 45, 43, 8, 35)
>>> max(t1)
45
>>> t2=('python', 'java', 'C++')
>>> max(t2)
'python'

min()

If the tuple contains numbers, the lowest number will be returned. If the tuple contains strings, the one that comes first in alphabetical order will be returned.

>>> t1=(12,45,43,8,35)
>>> min(t1)
8
>>> t2=('python', 'java', 'C++')
>>> min(t2)
'C++'

Note that if the tuple object contains strings as well as numeric items, max() and min() functions throw error.

>>> t1=(1,'Test', 12.22)
>>> max(t1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'