What is a Tuple ?
Tuples are built-in datatype in python that are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable. A tuple is denoted by parentheses ( )
Features :
Tuples are Ordered
Tuples are Immutable - meaning once a tuple is created, the values cannot be changed.
Allow Duplicates
Store Multiple data types
Each item in a tuple has a position called an index. Indexing starts from 0.
numbers = (10, 20, 30, 40, 50)| Value | 10 | 20 | 30 | 40 | 50 |
|---|---|---|---|---|---|
| Forward Index | 0 | 1 | 2 | 3 | 4 |
| Negative Index | -5 | -4 | -3 | -2 | -1 |
Accessing Tuple Items Using Indexing
Each element in a tuple has a position known as an index. Python uses zero-based indexing, so the first item has index 0.
1. Access the First Item
nums = (5, 10, 15, 20) print(nums[0]) # Output: # 52. Access Any Item by Index
fruits = ("apple", "banana", "cherry") print(fruits[2]) # Output: # cherryTrying to access an index outside the range raises an IndexError.
Negative Indexing
Python supports negative indexing to access items from the end
nums = (5, 10, 15, 20) print(nums[-1]) print(nums[-3]) # Output: # 20 # 10Here:
-
-1refers to the last item -
-3refers to the third-from-last item
Slicing Tuples
You can access a sub-tuple using slicing. The syntax is:
This extracts items from index start up to (not including) index end.
1. Slice From Start to a Position
letters = ("a", "b", "c", "d", "e") print(letters[0:3]) # Output: # ('a', 'b', 'c')2. Slice From a Position to End
letters = ("a", "b", "c", "d", "e") print(letters[2:]) # Output: # ('c', 'd', 'e')3. Full Slice (Copy Entire Tuple)
letters = ("a", "b", "c", "d", "e") print(letters[:]) # Output: # ('a', 'b', 'c', 'd', 'e')Iterating Through a Tuple
You can use a for loop to access each item in a tuple
fruits = ("apple", "banana", "cherry") for item in fruits: print(item) # Output: # apple # banana # cherryTuple Unpacking
You can extract values into separate variables
person = ("Alice", 25, "Delhi") name, age, city = person print(name) print(age) print(city) # Output: # Alice # 25 # DelhiThis assigns each element to its corresponding variable.
Important Notes
-
Tuples are immutable — you cannot change items after creation.
-
Indexing and slicing work the same way as in lists.
-
Negative indexing lets you access items from the end.