- A tuple is an immutable list means non-changeable list.
- Tuples are ordered in nature.
- Values can be accessed by index.
- Various operations can be performed like Iteration, looping , concatenation.
- Used when data is fixed and not require any changes.
Syntax
tuple_name = (item1,item2...itemN)
tuple_name =(item1 ,) # for single item comma is required at end
Accessing values of tuples
persons = ('Akshat','Raju','Bhanu','Naresh','Pareek')
for i in persons:
print(i)
OUTPUT :
Akshat
Raju
Bhanu
Naresh
Pareek
You cannot modify the tuples as they are immutable
persons = ('Akshat','Raju','Bhanu','Naresh','Pareek')
persons[0]='Akshita'
print(persons[0])
OUTPUT : TypeError: 'tuple' object does not support item assignment
persons = ('Akshat','Raju','Bhanu','Naresh','Pareek')
try :
del persons[0]
except :
print("Tuples items cannot be deleted")
OUTPUT : Tuples items cant be deleted
Assigning tuples values to multiple variables at once
persons = ('Akshat','Raju')
(first, second) = persons
print(first)
print(second)
OUTPUT :
Akshat
Raju
Deleting a tuple
persons = ('Akshat','Raju')
del persons
To convert tuple into list
persons = ('Akshat','Raju','Goli')
persons_list=list(persons)
print(persons_list)
OUTPUT : ['Akshat', 'Raju', 'Goli']