In Python, Tuples can be formed by placing a sequence of elements side by side separated by comma(,) inside parentheses.
The difference between a tuple
and list
is that tuples are immutable(they cannot be altered or modified) whereas list can be changed and sorted.
Tuples are useful when you want to protect values from updating or changing.
Creating Tuples
Example: Creating tuples using parentheses.
t = (25, 13.12, "This is a tuple")
print(t)
#PYTHON OUTPUT
(25, 13.12, 'This is a tuple')
Example: Creating tuples using constructors.
t = tuple((25, 13.12, "This is a tuple"))
print(t)
#PYTHON OUTPUT
(25, 13.12, 'This is a tuple')
Accessing tuples
This is same as accessing the list. We need to specify the index of the value we want.
Example
t = tuple((25, 13.12, "This is a tuple"))
print(t[2])
#PYTHON OUTPUT
This is a tuple
Accessing nested tuples
Example
t = tuple((
(1,2,3,4),
(10.25,12.10,14.33),
('a','b',)
))
print(t)
#PYTHON OUTPUT
((1, 2, 3, 4), (10.25, 12.1, 14.33), ('a', 'b'))
Example: Accessing nested tuples
t = tuple((
(1,2,3,4),
(10.25,12.10,14.33),
('a','b',)
))
print("Accessing tuple inside a tuple")
print(t[1])
print("Accessing 1st indexed tuples 2nd indexed value. ")
print(t[1][2])
#PYTHON OUTPUT
Accessing tuple inside a tuple
(10.25, 12.1, 14.33)
Accessing 1st indexed tuple 2nd indexed value.
14.33
To count the elements in tuple use python's built-in method 'len()'
Example
t=tuple((1,2,3,))
print(len(t))
#PYTHON OUTPUT
3
To check if the value present in the tuple.
Example
t=tuple((1,2,3,))
if 3 in t:
print("Yes exists")
else:
print("Does not exists")
#PYTHON OUTPUT
Yes exists
Example
t=tuple((1,2,3,))
if 31 in t:
print("Yes exists")
else:
print("Does not exists")
#PYTHON OUTPUT
Does not exists
To check whether the index exists in tuple use try...except
block.
Example
t=tuple((1,2,3,))
try:
t[5]
print("Index exists")
except IndexError:
print("Index does not exists.")
#PYTHON OUTPUT
Index does not exists.
As tuples are immutables their values cannot be updated nor you can remove items from the tuple.
Example
t=tuple((1,2,3,))
t[1]=222
print(t)
#PYTHON ERROR OUTPUT
TypeError: 'tuple' object does not support item assignment
To delete a tuple completely.
Example
t=tuple((1,2,3,))
del t
print(t)
#PYTHON ERROR OUTPUT
name 't' is not defined #because the tuple as already deleted.
Top comments (0)