Tuples in python are collection of objects which is separated by comma (,
) , tuples are similar to list except the fact that tuples are immutable (means once defined it cannot be changed) collection of objects or data is start with (
and ends with )
.
Example 1 :
tuple1 = ('edu','1','techs')
tuple2 = ('edu-techs',1,2,3)
print(tuple1)
print(tuple2)
Output :
('edu', '1', 'techs')
('edu-techs', 1, 2, 3)
Example 2 :
# Tuple immutability
tuple1[2] = '123'
print(tuple1)
Output :
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[2]='123'
TypeError: 'tuple' object does not support item assignment
Slicing Python Tuples :
Slicing in tuples is totally similar to slicing in python List .
tuple3 = (0 ,1, 2, 3)
print(tuple3[1:])
print(tuple3[::-1])
print(tuple3[2:4])
Output :
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Converting List or String to Tuple :
list1 = [0, 1, 2]
print(tuple(list1)) # list to tuple
print(tuple('python')) # string 'python' to tuple
Output :
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Operations That cannot be work in Python Tuples :
- We cannot update a tuple which is already defined or created.
- Once a tuple is defined it cannot be deleted.
- we cannot increase length of a tuple which is already defined or created.
- We cannot append into a already defined tuple.