Python | Tuple Method and Function
len() Function
len() is used for get the length of tuple
Example
tuple = ('mango' ,' banana', 'apple', 'mango' , 'graps' , 'apple')
print(len(tuple))
Output
6
type() Function
type() Function are return the type of tuple
Example
tuple = ('mango' ,' banana', 'apple', 'mango' , 'graps' , 'apple')
print(type(tuple))
Output
<class 'tuple'>
tuple() Function
tuple() are used to create tuple
Example
tup = tuple (('mango' ,' banana', 'apple', 'mango' , 'graps' , 'apple'))
print(type(tup))
Output
('mango' ,' banana', 'apple', 'mango' , 'graps' , 'apple')
Tuple Update
Tuples are unchangeable, means you cannot any changes in tuple add ,remove item after create tuple
Once you create a tuple you cannot any changes in that tuple values but You can convert in list , changes in list , then convert in tuple
Example
x = ("graps", "orange", "mango")
y = list(x)
y[1] = "papaya"
x = tuple(y)
print(x)
Output
('graps', 'papaya', 'mango')
If you direct add then show Error
Example
x = ("graps", "orange", "mango")
x[1] = "papaya"
print(x)
Output
Traceback (most recent call last):
File "./prog.py", line 3, in <module>
TypeError: 'tuple' object does not support item assignment
Remove item
same as first convert list, remove item , convert in tuple
Example
x = ("graps", "orange", "mango")
y = list(x)
y.remove("graps")
x = tuple(y)
print(x)
Output
( 'orange', 'mango')