Tuple in Python programming | Hands on coding

  • Tuple in Python
  • Tuple in python is a collection of data of different data types.
  • We can not change the value of tuples.
  • tuple is used to store tuple of values.
  • A tuple is created using parentheses.
str_tuple=("Apple","Orange","Mango")
int_tuple=(15,25,36,84,59)
float_tuple=(2.3,5.6,1.4,9.6)
mixed_tuple=("Easy",205,25.3)
  • The Value of tuple can be accessed using index number.
  • The Index number is always an integer value and starts with 0.

fruit_tuple=("Apple","Orange","Mango")
print("I like ",fruit_tuple[0])
print("I like ",fruit_tuple[2])
"""
***Output***
I like  Apple
I like  Mango
"""

int_tuple=(5,10,15,20,25,30,35,40,45,50)
#Print will start at index 1  and end at index 4 
print(int_tuple[1:4])
"""
***Output***
(10, 15, 20)
"""
  • The Negative indexes start from the end of the tuple.
  • Negative index always starts with -1.

fruit_tuple=("Apple","Orange","Mango")
print(fruit_tuple[-3])#Apple
print(fruit_tuple[-2])#Orange
print(fruit_tuple[-1])#Mango
"""
***Output***
Apple
Orange
Mango
"""

fruit_tuple=("Apple","Orange","Mango")
for name in fruit_tuple:
    print("I like ",name)
"""
***Output***
I like  Apple
I like  Orange
I like  Mango
"""

fruit_tuple=("Apple","Orange","Mango")
#this line will generate error
fruit_tuple[1]="Banana"
  • We can update the value of tuple using list.

fruit_tuple=("Apple","Orange","Mango")
print("Tuple Before Updation:",fruit_tuple)
#Convert tuple into list
fruit_list=list(fruit_tuple)
#Update Orange with Banana
fruit_list[1]="Banana"
#Convert list into tuple
fruit_tuple=tuple(fruit_list)
print("Tuple after Updation:",fruit_tuple)

"""
***Output***
Tuple Before Updation: ('Apple', 'Orange', 'Mango')
Tuple after Updation: ('Apple', 'Banana', 'Mango')
"""

fruit_tuple=("Apple","Orange","Mango")
print("Length of tuple is ",len(fruit_tuple))
"""
***Output***
Length of tuple is  3
"""
  • Tuples are unchangeable.

fruit_tuple=("Apple","Orange","Mango")
#this line will generate an error
fruit_tuple.append("Banana")

fruit_tuple=("Apple","Orange","Mango")
print("Fruit tuple:",fruit_tuple)
del fruit_tuple;
print("Deleted successfully")
#this line will generate error
print(fruit_tuple)
"""
***Output***
Fruit tuple: ('Apple', 'Orange', 'Mango')
Deleted successfully
NameError: name 'fruit_tuple' is not defined
"""