TUPLE
Tuple is one of the built-in data types in Python. A Python tuple is a sequence of comma separated
items, enclosed in parentheses (). The items in a Python tuple need not be of same data type.
Example
tup1 = ("Rohan", "Physics", 21, 69.75)
tup2 = (1, 2, 3, 4, 5)
tup3 = ("a", "b", "c", "d")
tup4 = (25.50, True, -55, 1+2j)
The empty tuple is written as two parentheses containing nothing –
tup1 = ();
Following are the points to be noted −
• In Python, tuple is a sequence data type. It is an ordered collection of items. Each item in
the tuple has a unique position index, starting from 0.
• In C/C++/Java array, the array elements must be of same type. On the other hand, Python
tuple may have objects of different data types.
• Python tuple and list both are sequences. One major difference between the two is,
Python list is mutable, whereas tuple is immutable. Although any item from the tuple can
be accessed using its index, and cannot be modified, removed or added.
Accessing Values in Tuples
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print ("tup1[0]: ", tup1[0]);
print ("tup2[1:5]: ", tup2[1:5]);
output
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
• Updating Tuples - Tuples are immutable which means you cannot update or change the
values of tuple elements. You are able to take portions of existing tuples to create new tuples
tup1 = (12, 34.56); tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2; print (tup3);
output
(12, 34.56, 'abc', 'xyz')
• Delete Tuple Elements - Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with the undesired elements
discarded.
tup = ('physics', 'chemistry', 1997, 2000);
print (tup);
del tup;
print ("After deleting tup : ");
print (tup);
output
NameError: name 'tup' is not defined
• Python Tuple Operations - In Python, Tuple is a sequence. Hence, we can concatenate
two tuples with + operator and concatenate multiple copies of a tuple with "*" operator. The
membership operators "in" and "not in" work with tuple object.
Python Expression Results Description
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
• Indexing, Slicing, and Matrixes - Because tuples are sequences, indexing and slicing
work the same way for tuples as they do for strings.
L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the
right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
• No Enclosing Delimiters - Any set of multiple objects, comma-separated, written without
identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as
indicated in these short examples −
print ('abc', -4.24e93, 18+6.6j, 'xyz');
x, y = 1, 2;
print ("Value of x , y : ", x,y);
Output
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
• Unpack Tuple Items - The term "unpacking" refers to the process of parsing tuple items in
individual variables. In Python, the parentheses are the default delimiters for a literal representation
of sequence object.
Following statements to declare a tuple are identical.
>>> t1 = (x,y)
>>> t1 = x,y
>>> type (t1)
<class 'tuple'>
Example
tup1 = (10,20,30)
x, y, z = tup1
print ("x: ", x, "y: ", "z: ",z)
Output
x: 10 y: 20 z: 30
• ValueError While Unpacking a Tuple - If the number of variables is more or less than the
length of tuple, Python raises a ValueError.
Example
tup1 = (10,20,30)
x, y = tup1
x, y, p, q = tup1
Output
x, y = tup1
^^^^
ValueError: too many values to unpack (expected 2)
x, y, p, q = tup1
^^^^^^^^^^
ValueError: not enough values to unpack (expected 4, got 3)
• Unpack Tuple Items Using Asterisk (*) - In such a case, the "*" symbol is used for
unpacking. Prefix "*" to "y", as shown below −
Example
tup1 = (10,20,30)
x, *y = tup1
print ("x: ", "y: ", y)
Output
x: y: [20, 30]
The first value in tuple is assigned to "x", and rest of items to "y" which becomes a list.
• Loop Through Tuple Items - Looping through tuple items in Python refers to iterating over
each element in a tuple sequentially.
In Python we can loop through the items of a tuple in various ways, with the most common being the for
loop. We can also use the while loop to iterate through tuple items, although it requires additional
handling of the loop control variable explicitly i.e. an index.
• Loop Through Tuple Items with For Loop - A for loop in Python is used to iterate over a
sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to
execute a block of code repeatedly for each item in the sequence.
In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations
or logic based on that item's value. We can loop through tuple items using for loop by iterating over each
item in the tuple.
Syntax
for item in tuple:
# Code block to execute
Example
tup = (25, 12, 10, -21, 10, 100)
for num in tup:
print (num, end = ' ')
Output
25 12 10 -21 10 100
• Loop Through Tuple Items with While Loop - A while loop in Python is used to repeatedly
execute a block of code as long as a specified condition evaluates to "True".
We can loop through tuple items using while loop by initializing an index variable, then iterating through
the tuple using the index variable and incrementing it until reaching the end of the tuple.
Syntax
while condition:
# Code block to execute
Example
my_tup = (1, 2, 3, 4, 5)
index = 0
while index < len(my_tup):
print(my_tup[index])
index += 1
Output
• Loop Through Tuple Items with Index - An index is a numeric value representing the
position of an element within a sequence, such as a tuple, starting from 0 for the first element.
We can loop through tuple items using index by iterating over a range of indices corresponding to the
length of the tuple and accessing each element using the index within the loop.
Example
tup = (25, 12, 10, -21, 10, 100)
indices = range(len(tup))
for i in indices:
print ("tup[{}]: ".format(i), tup[i])
Output
tup[0]: 25
tup[1]: 12
tup[2]: 10
tup[3]: -21
tup[4]: 10
tup[5]: 100
• Joining Tuples in Python - Joining tuples in Python refers to combining the elements of multiple
tuples into a single tuple. This can be achieved using various methods, such as concatenation, list
comprehension, or using built-in functions like extend() or sum().
Joining tuples does not modify the original tuples but creates a new tuple containing the combined
elements.
Joining Tuples Using Concatenation ("+") Operator
The concatenation operator in Python, denoted by +, is used to join two sequences, such as strings, lists,
or tuples, into a single sequence. When applied to tuples, the concatenation operator joins the elements
of the two (or more) tuples to create a new tuple containing all the elements from both tuples.
We can join tuples using the concatenation operator by simply using the + symbol to concatenate them.
Example
T1 = (10,20,30,40)
T2 = ('one', 'two', 'three', 'four')
joined_tuple = T1 + T2
print("Joined Tuple:", joined_tuple)
Output
Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
Joining Tuples Using List Comprehension
List comprehension is a concise way to create lists in Python. It is used to generate new lists by applying
an expression to each item in an existing iterable, such as a list, tuple, or range. The syntax for list
comprehension is −
new_list = [expression for item in iterable]
This creates a new list where expression is evaluated for each item in the iterable.
We can join a tuple using list comprehension by iterating over multiple tuples and appending their
elements to a new tuple.
Example
T1 = (36, 24, 3)
T2 = (84, 5, 81)
joined_tuple = [item for subtuple in [T1, T2] for item in subtuple]
print("Joined Tuple:", joined_tuple)
Output
Joined Tuple: [36, 24, 3, 84, 5, 81]
Joining Tuples Using extend() Function
The Python extend() function is used to append elements from an iterable (such as another list) to the end
of the list. This function modifies the original list in place, adding the elements of the iterable to the end
of the list.
The extend() function is not used for joining tuples in Python. It is used to extend a list by appending
elements from another iterable (such as another list), effectively merging the two lists together.
Example
T1 = (10,20,30,40)
T2 = ('one', 'two', 'three', 'four')
L1 = list(T1)
L2 = list(T2)
[Link](L2)
T1 = tuple(L1)
print ("Joined Tuple:", T1)
Output
Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
Join Tuples using sum() Function
In Python, the sum() function is used to add up all the elements in an iterable, such as a list, tuple, or set.
It takes an iterable as its argument and returns the sum of all the elements in that iterable.
We can join a tuple using the sum() function by providing the tuple as an argument to the sum() function.
However, since the sum() function is specifically designed for numeric data types, this method only works
for tuples containing numeric elements. It will add up all the numeric elements in the tuple and return
their sum.
Syntax
result_tuple = sum((tuple1, tuple2), ())
Here, the first argument is a tuple containing the tuples to be joined. The second argument is the
starting value for the sum. Since we are joining tuples, we use an empty tuple () as the starting value.
Example
T1 = (10,20,30,40)
T2 = ('one', 'two', 'three', 'four')
T3 = sum((T1, T2), ())
print ("Joined Tuple:", T3)
Output
Joined Tuple: (10, 20, 30, 40, 'one', 'two', 'three', 'four')
Joining Tuples using for Loop
A for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range) and
executing a block of code for each element in the sequence. The loop continues until all elements have
been processed.
We can join a tuple using a for loop by iterating over the elements of one tuple and appending each
element to another tuple with the "+=" operator.
Example
T1 = (10,20,30,40)
T2 = ('one', 'two', 'three', 'four')
for t in T2:
T1+=(t,)
print (T1)
Output
(10, 20, 30, 40, 'one', 'two', 'three', 'four')
Built-in Functions with Tuples
1. cmp() - The Python Tuple cmp() method is used to compare the elements of two tuples. The
elements of tuples can be of same or different data types. If elements are of the same type,
compare them and return the result. If elements are different types, check to see if they are
numbers.
There are two different cases in the comparison done by this method.
They are as follows −
Case 1: Suppose the tuple contains only numbers, the method compares elements from left to
right. If a greater number is encountered in a tuple, the tuple containing it is declared greater and
the further comparisons are halted. But if all the elements are equal, the tuples are declared
equal.
Case 2: If there are multiple data types in the tuple, the method compares it based on the order
these data types and are sorted. For example, a string type is greater than any number type,
hence, if a tuple contains a string, it is greater.
Note: This method is only executable in Python 2.x and does not work in Python 3.x.
Syntax
Following is the syntax of the Python Tuple cmp() method −
cmp(tuple1, tuple2)
Parameters
• tuple1 − This is the first tuple to be compared
• tuple2 − This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If elements are
different types, check to see if they are numbers.
• If numbers, perform numeric coercion if necessary and compare.
• If either element is a number, then the other element is "larger" (numbers are
"smallest").
• Otherwise, types are sorted alphabetically by name.
Example
tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
print cmp(tuple1, tuple2)
print cmp(tuple2, tuple1)
tuple3 = tuple2 + (786,);
print cmp(tuple2, tuple3)
Output
-1
-1
2. len() - method returns the number of elements in the tuple.
Syntax
len(tuple)
Parameters tuple − This is a tuple for which number of elements are to be counted.
Return Value - This method returns the number of elements in the tuple.
Example
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))
Output
First tuple length : 3
Second tuple length : 2
3. max() method returns the elements from the tuple with maximum value.
Syntax
max(tuple)
Parameters tuple − This is a tuple from which max valued element has to be returned.
Return Value - This method returns the elements from the tuple with maximum value.
Example
tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))
Output
Max value element : zara
Max value element : 700
4. min() method returns the elements from the tuple with minimum value.
Syntax
min(tuple)
Parameters tuple − This is a tuple from which min valued element has to be returned.
Return Value - This method returns the elements from the tuple with minimum value.
Example
tuple1, tuple2 = ('xyz', 'zara', 'abc'), (456, 700, 200)
print ("min value element : ", min(tuple1))
print ("min value element : ", min(tuple2))
Output
min value element : abc
min value element : 200
5. tuple() method is used to convert a list of items into tuples.
Syntax
tuple(seq)
Parameters seq − This is a sequence to be converted into tuple.
Return Value - This method returns this tuple.
Example
aList = ['xyz', 'zara', 'abc']
aTuple = tuple(aList)
print ("Tuple elements : ", aTuple)
Output
Tuple elements : ('xyz', 'zara', 'abc')
6. tuple. index(obj) - The index() method of tuple class returns the index of first occurrence of the
given item.
Syntax
tuple. Index(obj)
Return value - The index() method returns an integer, representing the index of the first occurrence
of "obj".
Example
tup1 = (25, 12, 10, -21, 10, 100)
print ("Tup1:", tup1)
x = [Link](10)
print ("First index of 10:", x)
Output
Tup1: (25, 12, 10, -21, 10, 100)
First index of 10: 2
7. Tuple .count(obj) - The count() method in tuple class returns the number of times a given
object occurs in the tuple.
Syntax
tuple. Count(obj)
Return Value
Number of occurrence of the object. The count() method returns an integer.
Example
tup1 = (10, 20, 45, 10, 30, 10, 55)
print ("Tup1:", tup1)
c = [Link](10)
print ("count of 10:", c)
Output
Tup1: (10, 20, 45, 10, 30, 10, 55)
count of 10: 3