Operations and Usage of Tuple - Python

  • Tuple is a data structure in  python.
  • It is used to store the data like lists.
  • The only difference is it is not  mutable.
  • We cannot able to perform insert, update and delete operations like lists.
  • That's why tuples are faster than lists.

How to create a tuple in python ?

# case1
t = tuple()
print(t)
# Output: ()
print(type(t))
# Output: tuple
# case2
t = ()
print(t)
# Output: ()
print(type(tuple))
# Output: tuple
# tuple with elements
t = (1)
print(type(t))
# Output: tuple
# we must use comma for single element of a tuple
t = (1,)
print(type(t))
# Output: tuple
t = (1,"a","3")
print(type(t))
# Output: tuple

How to access elements in tuple python ?

We can access elements in tuple through indexes.
t = (1,"a","3")
# positve indexes
print(t[0])
# Output: 1
print(t[1])
# Output: a
print(t[2])
# Output: 3
# negative indexes
print(t[-1])
# Output: 3
print(t[-2])
# Output: a
print(t[-3])
# Output: 1

How to count frequency or number of occurrences of an element in a list ?

t = (1,2,3,4,1,2,1,5,8,1,7,'a',5,1,2.5)
t.count(1)
# Output:
t.count(1)
# Output: 5
t.count('a')
# Output: 1
t.count("not found")
# Output: 0

How to find index of an element in a list ?

t = (1,2,3,4,1,2,1,5,8,1,7,'a',5,1,2.5)
print(t.index(1))
# Output: 0
print(t.index(5))
# Output: 7
print(t.index("not found"))
# Output: ValueError: tuple.index(x): x not in tuple
Note: "index" is a method. It takes single argument as an element and returns index value of first occurrence.

How to add two or more tuple objects to get a new tuple object?

t1 = (1, "a", [123, "hi"])
t2 = (2, 3, "hi")
print(t1 + t2)
# Output: (1, 'a', [123, 'hi'], 2, 3, 'hi')
t3 = t1 + t2
print(t3)
# Output: (1, 'a', [123, 'hi'], 2, 3, 'hi')

Try the following code and see output.

t = (1, "a", 2.25)
print(t * 2)
# Output: (1, 'a', 2.25, 1, 'a', 2.25)
print(t * 3)
# Output: (1, 'a', 2.25, 1, 'a', 2.25, 1, 'a', 2.25)

Buy a product to Support me