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() and clear() on tuples. Tuples are generally used to store data which should not be modified and retrieve that data on demand.
We can create a tuple by writing elements separated by commas inside parentheses (). The elements can be of same datatype or different types. For example, to create an empty tuple, we can simply write empty parenthesis, as:
tup1 = () #empty tuple
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,)
Here is a tuple with different types of elements:
tup3 = (10, 20, -30.1, 40.5, 'Hyderabad', 'New Delhi')
We can create a tuple with only one of type of elements also, like the following:
tup4 = (10, 20, 30) #tuple with integers
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 #no braces
The point to remember is that if 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 into a tuple using the tuple() function.
list = [1, 2, 3] #take a list
tpl = tuple(list) #convert list into tuple
print(tpl) #display tuple
Another way to create a tuple is by using range() function that returns a sequence.
tpl= tuple(range(4, 9, 2)) #numbers from 4 to 8 in steps of 2
The preceding statements will give: (4, 6, 8)
Access Tuple Elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list.
tup = (50,60,70,80,90,100)
Indexing represents the position number of the element in the tuple. Now, tup represents the 0th element, tup represents the 1st element and so on.
The preceding will give: 50
student = (10, 'Naresh kumar', 50,60,65,61,70)
rno, name = student[0:2]
marks = student[2:7]
for i in marks: