Programming Essentials Python - Overview of Collections - Accessing Elements - tuples

Let us see details related to operations on tuples. Unlike other collections (list, set, dict) we have limited functions with tuple in Python.

  • tuple is by definition immutable and hence we will not be able to add elements to a tuple or delete elements from a tuple.

  • Only functions that are available are count and index.

  • count gives the number of times an element is repeated in a tuple.

  • index returns the position of the element in a tuple. index can take up to 3 arguments - element, start, and stop.

t = (1, 2, 3, 4, 4, 6, 1, 2, 3)
help(t)
t.count?
t.count(4)
t.count(9)
t.index?
t.index(2) # Scans all the elements
t.index(2, 3) # Scans all the elements starting from the 4th
t.index(2, 3, 5) # throws ValueError, scans from the 4th element till the 5th element
t.index(9)
t.index(6, 3, 5) # throws ValueError, scans from the 4th element till the 5th element
t.index(6, 3, 6) 

Hands-On Tasks

Let’s have some hands-on tasks related to tuple operations:

  1. Create a tuple with elements (5, 3, 2, 5, 1) and use the count function to find how many times 5 appears.
  2. Create a tuple with elements (7, 6, 4, 2, 3) and use the index function to find the position of 4 in the tuple.

Conclusion

In this article, we discussed the operations that can be performed on tuples in Python. We explored functions like count and index that help in manipulating tuples. It’s important to remember that tuples are immutable in nature and have limited built-in functions compared to other collections in Python. Practice these operations to enhance your understanding further. Keep learning and exploring new concepts in Python!

Watch the video tutorial here