Python Tuples: An Overview with Examples and Code Snippets - 2023
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.
Creating a Tuple in Python
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])
Accessing Elements of a Tuple in Python
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])
Commonly Used Tuple Methods in Python
Tuples in Python have several built-in methods that allow you to manipulate them. Here are some of the most commonly used methods:
- count() - returns the number of times a specified element appears in the tuple.
# 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.
Previous Next
NEWSLETTER
Coding Bytes by Codzify
Welcome to Coding Bytes, your weekly source for the latest coding tutorials and insights in small byte sized content.
Join 615+ Subscribers
Subscribe on LinkedIn