Tuples in Python
Tuples in Python
A tuple is a Python sequence which stores a group of elements or items. Tuples are similar to
lists but the main difference is tuples are immutable whereas lists are mutable. Since tuples
are immutable, once we create a tuple we cannot modify its elements. Hence we cannot
perform operations like append(), extend(), insert(), remove(), pop() arid clear() on tuples.
Tuples are generally used to store data which should not be modified and retrieve that data on
demand
Creating Tuples
We can create a tuple by writing elements separated by commas inside parentheses (). The
elements can be of the same datatype or different types. For example, to create an empty
tuple, we can simply write empty parenthesis, as:
tup1 = ()
If we want to create a tuple with only one element, we can mention that element in
parentheses and after that a comma is needed, as:
tup2=(10,)
We can create a tuple with only one of type of elements also, like the
following: tup4= (10, 20, 30)
If we do not mention any brackets and write the elements separating them by commas,
then they are taken by default as a tuple. See the following example:
tup5 = 1, 2, 3, 4
The point to remember is that if you do not use any brackets, it will become a tuple and not a
list or any other datatype.
It is also possible to create a tuple from a list. This is done by converting a list ints tuple
using the tuple() function. Consider the following example:
list [1, 2, 3]
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
tpl=tuple(list)
print(tpl)
print (tup[0])
Similarly, negative indexing is also possible. For example, tup[-1] indicates the last element
and tup[-2] indicates the second element from the end and so on. Consider the following
statement:
print(tup[-1])
If you write,
print (tup[-6])
Then the following output appears:
50
Slicing represents extracting a piece or part of the tuple. Slicing is done in the format. start
stop: stepsize). Here, 'start' represents the position of the starting element and stop represents
the position of the ending element and the stepsize indicates the incrementation. If the tuple
contains 'n' elements, the default values will be 0 for start and n-1 for 'stop' and 1 for 'stepsize’.
For example, to extract all the elements from the tuple, we can write:
print(tup[:])
Similarly, to extract every other element, i.e. alternate elements, we can write:
print(tup[::2])
The following output appears:
(50, 70, 90)
Negative values can be given in the slicing. If the 'step size' is negative, the elements
are extracted in reverse order as:
print (tup[::-2])
When the step size is not negative, the elements are extracted from left to right. In the following
example, starting position -4 indicates the 4th element from the last. Ending position -1
indicates the last element. Hence, the elements from 4th to one element before the ending
element (left to right) will be extracted.
In most of the cases, the extracted elements from the tuple should be stored in separate
variables for further use. In the following example, we are extracting the first two elements from
the student' tuple and storing them into two variables.
student (10, 'Vinay kumar’, 50,60,65,61,70)
rno, name student [0:2]
Now, the variable ‘rno’ represents 10 and 'name' represents Vinaykumar. Consider the
following statement:
print (rno)
If we want to retrieve the marks of the student from 'student' tuple, we can do it as:
marks=student [2:7]
for i in marks:
print (i)
50
60
65
61
70
fees=(25000.00,)*4
print (fees)
Now, we can concatenate the ‘student’ and ‘fees' tuples together to form a new tuple
‘student1' as:
student1=student+fees
print(student1)
Searching whether an element is a member of the tuple or not can be done using in' and not in
operators. The in' operator returns True if the element is a member. The 'not in operator
returns True if the element is not a member. Consider the following statements:
name=’Vinay kumar’
name in student1
The repetition operator repeats the tuple elements. For example, we take a tuple "tpl' and
repeat its elements for 4 times as:
tpl= (10, 11, 12)
tpl1 = tp1*3
print (tpl1)
We will write a program to accept elements of a tuple from the keyboard and find their sum and
average. In this program, we are using the following statement to accept elements from the
keyboard directly in the format of a tuple (i.e. inside parentheses).
num=eval(input("Enter elements in (): "))
tuple. Ex:
Output:
When the above program asks the user for entering the elements, the user can type the
elements inside the parentheses as: (1,2,3,4,5,6) or without any parentheses 1,2,3,4,5,6.
When a group of elements are entered with commas (,), then they are default taken as a tuple
in Python.
In the program below, first we enter the elements separated by commas. These elements
are stored into a string 'str' as:
Then each element of this string is converted into integer and stored into a list ‘lst'
This list can be converted into a tuple using tuple() function as:
tup tuple(lst)
Later, index() method is used to find the first occurrence of the element 'ele'
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
as: pos=tup.index(ele)
If the 'ele' is not found in the tuple, then there will be an error by the name ValueError'
which should be handled using try and except blocks which is shown in the program
Output:
Nested Tuples
A tuple inserted inside another tuple is called a nested tuple. For
example, tup(50.60,70,80,90,(200, 201))
Observe the last parentheses in the tuple ‘tup', ie. (200, 201). These parentheses represent
that it is a tuple with 2 elements inserted into the tuple ‘tup'. The tuple (200, 201) is called a
nested tuple as it is inside another tuple.
The nested tuple with the elements (200, 201) is treated as an element along with other
elements in the tuple ‘tup'. To retrieve the nested tuple, we can access it as an ordinary
element as tup[5] as its index is 5. Now, consider the following statement:
print('Nested tuple=’, tup[6])
Every nested tuple can represent a specific data record. For example, to store 4
employees data in 'emp' tuple, we can write:
will sort the tuple emp' in ascending order of the 0th element in the nested tuples, i.e
identification number. If we want to sort the tuple based on employee name, which is the
1st element in the nested tuples, we can use a lambda expression as:
Here, key indicates the key for the sorted() function that tells on which element sorting should
be done. The lambda function: lambda x: x[1] indicates that x[1] should be taken as the key
that is nothing but the 1st element. If we want to sort the tuple based on salary, we can use the
lambda function as: lambda x: x[2].
Output:
First of all, copy the elements of ‘x' from 0th position to pos-2 position into ‘y’ as:
y=x[0:pos-1]
y=y+new
Concatenate the remaining elements (from pos-1 till end) of x to the new tuple y. The total
tuple can be stored again with the old name ‘x’.
x=y+x[pos-1:]
Output:
This program works well with strings. Of course the same program can be used with
integers also, if we change the input statement that accepts an integer number as:
as: y=x[0:pos-1]
2. Concatenate the new element to the new tuple ‘y’ .Thus the new element is stored in
the position of the element being modified.
y=y+new
3. Now concatenate the remaining elements from x' by eliminating the element which is at
‘pos-1’. It means we should concatenate elements from ‘pos' till the end. The total tuple can
be assigned again to the old name ‘x’.
x=y+x[pos:]
Output:
1. First of all, copy the elements of x' from 0th position to pos-2 position into y'
as: y = x[0:pos-1]
2. Now concatenate the remaining elements from 'x' by eliminating the element which is at
Learnvista Pvt Ltd.
2nd Floor, 147, 5th Main Rd, Rajiv Gandhi Nagar HSR Sector 7,Near Salarpuria Serenity, Bengaluru, Karnataka 560102
Mob:- +91 779568798, Email:- [email protected]
‘pos-1'. It means we should concatenate elements from 'pos' till the end. The tota tuple can
be assigned again to the old name 'x'.
x=y+x[pos:]
Ex:
Output: