Article by: Manish Methani
Last Updated: October 4, 2021 at 10:04am IST
Tuples are an essential data structure in Python that allow you to store a sequence of immutable elements. In this tutorial, you will learn what tuples are and how to use them in Python. We will also explore some of the most commonly used methods of tuples.
To create a tuple in Python, you use parentheses () and separate the elements with commas. You can also create a tuple using the built-in tuple() function.
# Creating a tuple using parentheses my_tuple = (1, 2, 3, 4, 5) # Creating a tuple using the tuple() function my_other_tuple = tuple([6, 7, 8, 9, 10])
You can access the elements of a tuple in Python using indexing. Indexing in Python starts from 0. You can also use negative indexing to access elements from the end of the tuple.
# Accessing the first element of my_tuple print(my_tuple[0]) # Accessing the last element of my_other_tuple print(my_other_tuple[-1])
Tuples in Python have several built-in methods that allow you to manipulate them. Here are some of the most commonly used methods:
# Counting the number of times 3 appears in my_tuple print(my_tuple.count(3))
2. index() - returns the index of the first occurrence of a specified element in the tuple.
# Finding the index of the first occurrence of 7 in my_other_tuple print(my_other_tuple.index(7))
In conclusion, Python Tuples are ordered and immutable collections of values, similar to lists, but with some key differences. The main advantage of using tuples over lists is that tuples are immutable, which means that once they are created, their contents cannot be changed. This property makes tuples more efficient for certain operations and also allows them to be used as keys in dictionaries.