A tuple is one of four built-in data types in Python used to store collections of data. Tuple operations are those that can be performed on the elements in the tuple data structure. Let us look at some of the most widely used tuple operations in Python.
1. Count Occurrences of an Element in a Tuple
count() method is used to count the total occurrences of an element in the tuple. If the element is not found in the tuple, then the function returns 0.
tup1 = ( 1, 4, 7, 3, 6, 4, 1, 8, 4 )
# counts number of times 4 occurs in the tuple
print( tup1.count(4) )
# prints
3
2. Finding the Position of an Element in a Tuple
You can use the index() method to find the index/position of an element in the tuple. If there are more than one occurrences of an element in the tuple, then the function returns the index of the first occurrence.
tup1 = ( 1, 4, 7, 3, 6, 4, 1, 8, 4)
print( tup1.index(4) )
# prints
1
Note:
If you try to find the index of the element which is not present in the tuple, then the function throws a ValueError as:
ValueError: tuple.index(x): x not in tuple
3. How to Join Two or More Tuples
You can join two or more tuples using the + operator.
tup1 = ( 1, 2, 3 )
tup2 = ( 4, 5, 6 )
tup3 = tup1 + tup2
print( tup3 )
# prints
(1, 2, 3, 4, 5, 6)
4. How to Convert String to a Tuple
You can use the tuple() constructor to convert a string to a tuple by passing the string as a parameter to the tuple() constructor.
tup1 = tuple( "MAKEUSEOF" )
print( tup1 )
# prints
('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
5. How to Convert List to a Tuple
We can follow three approaches to convert a list to a tuple.
Approach 1: Using tuple() Constructor
tuple() constructor is used to convert a list to a tuple by passing the list as a parameter to the tuple() constructor.
list1 = [1, 2, 3, 4, 5, 6]
tup1 = tuple(list1)
print(tup1)
# prints
(1, 2, 3, 4, 5, 6)
Approach 2: Using a Loop Inside tuple() Constructor
It is a slight variation of the above approach. We are running a loop (using list comprehension) inside the tuple() constructor to create the tuple.
list1 = [ 1, 2, 3, 4, 5, 6 ]
tup1 = tuple( element for element in list1 )
print( tup1 )
# prints
(1, 2, 3, 4, 5, 6)
Approach 3: Using (*listName,)
This unpacks a list inside the tuple literal due to the presence of the single comma (,). This method is the fastest of the three approaches.
list1 = [1, 2, 3, 4, 5, 6]
tup1 = (*list1,)
print(tup1)
# prints
(1, 2, 3, 4, 5, 6)
6. How to Multiply Tuples
You can multiply the contents of the tuple any number of times using the * operator.
tup1 = ( 1, 2, 3 )
tup2 = tup1 * 3
print( tup2 )
# prints
(1, 2, 3, 1, 2, 3, 1, 2, 3)
7. How to Find Total Number of Elements in a Tuple
len() function is one of the most used inbuilt functions in Python. It is used to find the total number of items in an object. You can use the len() function with tuple to count the total number of elements in the tuple.
tup1 = ( 1, 2, 3 )
print( len( tup1 ) )
# prints
3
8. How to Find Minimum Element in a Tuple
min() function is used to find an element with the lowest value in the given tuple.
tup1 = ( 1, 2, 3 )
print("Minimum element in the tuple is: ")
print( min( tup1 ) )
# prints
Minimum element in the tuple is:
1
9. How to Find Maximum Element in a Tuple
max() function is used to find an element with the highest value in the given tuple.
tup1 = ( 1, 2, 3 )
print("Maximum element in the tuple is: ")
print( max( tup1 ) )
# prints
Maximum element in the tuple is:
3
10. How to Find the Sum of All Elements in a Tuple
sum() function is used to calculate the arithmetic sum of all elements in the tuple.
tup1 = ( 1, 2, 3 )
print("Sum of elements : ")
print( sum( tup1 ) )
# prints
Sum of elements :
6
11. any() Operation on Tuples
If one or more elements of the tuple have a boolean value True, then any() function returns True otherwise it returns False.
tup1 = ( False, False, False, True )
print( any( tup1 ) )
# prints
True
12. all() Operation on Tuples
You can use all() function to check if all the elements of the tuple have a Boolean value True. Even if any one element of the tuple has a Boolean value False, then the function returns False.
tup1 = ( True, True, True, False, True )
print( all( tup1 ) )
# prints
False
13. sorted() Operation on Tuples
You can use the sorted() function to return a sorted list in ascending order.
tup1 = ( 6, 1, 8, 3, 7, 2 )
print( sorted(tup1) )
print( type(sorted( tup1 )) )
# prints
[1, 2, 3, 6, 7, 8]
# Note that the return type is list
14. How to Shuffle a Tuple
Since tuples are immutable, they can’t be shuffled directly. We need to use lists to shuffle a tuple. We can shuffle a tuple using typecasting in three steps:
Step 1: Typecast tuple to a list
Step 2: Shuffle the list
Step 3: Typecast list back to a tuple
import random
old_tuple = ( 45, 46, 47, 48, 49 )
# Printing tuple
print("Old tuple:")
print(old_tuple)
# Typecasting tuple to list
list1 = list(old_tuple)
# Shuffling list
random.shuffle(list1)
# Typecasting list back to tuple
new_tuple = tuple(list1)
# Printing new shuffled tuple
print("New shuffled tuple:")
print(new_tuple)
# prints
Old tuple:
(45, 46, 47, 48, 49)
New shuffled tuple:
(45, 49, 46, 47, 48)
Note: Since the tuple is shuffled randomly, you may get a different output.
15. How to Convert List of Tuples to List of Lists
Using the list comprehension we can convert a list of tuples to a list of lists.
list1 = [ ('A', 'B'), ('C', 'D'), ('E', 'F') ]
print("List of tuples:")
print( list1 )
# List Comprehension
result = [ list(element) for element in list1 ]
print("List of lists:")
print(result)
# prints
List of tuples:
[('A', 'B'), ('C', 'D'), ('E', 'F')]
List of lists:
[['A', 'B'], ['C', 'D'], ['E', 'F']]
16. How to Convert List of Tuples to List of Strings
Using the list comprehension and join() method we can convert a list of tuples to a list of strings.
list1 = [ ('M', 'A', 'K', 'E'), ('U', 'S', 'E'), ('O', 'F') ]
print("List of tuples:")
print( list1 )
# List Comprehension with join() method
result = [ ''.join(element) for element in list1 ]
print("List of strings:")
print(result)
# prints
List of tuples:
[('M', 'A', 'K', 'E'), ('U', 'S', 'E'), ('O', 'F')]
List of strings:
['MAKE', 'USE', 'OF']
17. How to Reverse a Tuple
Using the slicing technique, we can reverse the tuple. A new copy of the tuple is created during this process.
old_tuple = ('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
print("Old tuple:")
print(old_tuple)
# Reversing tuple using slicing
new_tuple = old_tuple[::-1]
print("New tuple:")
print(new_tuple)
# prints
Old tuple:
('M', 'A', 'K', 'E', 'U', 'S', 'E', 'O', 'F')
New tuple:
('F', 'O', 'E', 'S', 'U', 'E', 'K', 'A', 'M')
Learning the Pythonic Way
Using tuple operations in Python you can perform a task with minimal lines of code. Get creative and explore the potential of tuples further to learn Python in a more Pythonic way.