When working with Python, we often need to store multiple values in a single variable. Python provides different data structures for this, and one of them is Tuple.
What is a Tuple?
A tuple is a built-in Python data structure used to store multiple values in a single variable.
The interesting thing about tuples is that they are ordered and immutable.
- Ordered: Elements maintain their insertion order.
- Immutable: Once a tuple is created, we cannot modify its elements.
How to Create a Tuple?
We use parentheses () to create a tuple.
my_tuple = ("Python", "Java", "JavaScript")
print(my_tuple)
Output:
('Python', 'Java', 'JavaScript')
How to Create an Empty Tuple?
An empty tuple is a tuple that contains no elements.
We can create an empty tuple using empty parentheses ().
empty_tuple = ()
print(empty_tuple)
print(type(empty_tuple))
Output:
()
<class 'tuple'>
Remember: An empty tuple () is different from an empty list [] and an empty set set().
Accessing Tuple Elements
We can access tuple elements using their index, just like lists.
languages = ("Python", "Java", "C++")
print(languages[0])
print(languages[1])
Output:
Python
Java
Can We Modify a Tuple?
No! Tuples are immutable.
Once created, we cannot directly add, remove, or change their elements.
numbers = (10, 20, 30)
numbers[0] = 100 # TypeError
Useful Tuple Methods
Python provides two main built-in tuple methods.
1. count()
Returns how many times an element appears.
numbers = (10, 20, 10, 30)
print(numbers.count(10))
Output: 2
2. index()
Returns the index of the first occurrence of an element.
numbers = (10, 20, 30)
print(numbers.index(20))
Output: 1
Tuple vs List
Both tuples and lists can store multiple values, but there is one major difference.
-
List: Uses square brackets
[]and is mutable. -
Tuple: Uses parentheses
()and is immutable.
When Should We Use Tuples?
Tuples are useful when:
- We want to store data that should not be changed.
- We want to represent fixed collections of values.
- We need to return multiple values from a function.
Final Thoughts
Python tuples are simple but useful data structures. Understanding when to use a list and when to use a tuple helps us write cleaner and more reliable Python code.
Top comments (0)