A Tuple in Python is a collection of elements that is ordered and immutable (we cannot change its elements after creation).
We create a tuple using round brackets ().
- Example of Tuple:
numbers = (10, 20, 30, 40, 50)
print(numbers)
print(numbers[0])
print(numbers[2])
Output:
(10, 20, 30, 40, 50)
10
30
Here:
- numbers[0] returns 10.
- numbers[2] returns 30.
- Tuple supports indexing.
Important Characteristics of Tuple:
Ordered collection.
Allows duplicate values.
Immutable (cannot change elements).
Supports indexing.
Allows different data types.
Faster for some operations than lists.
Tuple Methods:
Python has two main built-in tuple methods:
- count() – Counts how many times an element appears. numbers = (10, 20, 10, 30, 10) print(numbers.count(10))
Output:
3
- index() – Returns the index of an element's first occurrence. numbers = (10, 20, 30, 40) print(numbers.index(30))
Output:
2
- Can we modify a Tuple?
No. We cannot directly add, remove, or update tuple elements.
numbers = (10, 20, 30)
numbers[0] = 100
print(numbers)
Output:
TypeError
Because tuples are immutable.
- Difference Between List, Tuple and Set:
Feature List Tuple Set
Symbols {}
Ordered Yes Yes No
Duplicates Yes Yes No
Mutable Yes No Yes
Indexing Yes Yes No
Top comments (0)