Tuple Types in Python — Explained with Examples
A tuple in Python is an ordered, immutable collection of elements. Tuples are similar to lists, but unlike lists, you cannot modify (add, remove, or change) elements once a tuple is created.
1. Creating a Tuple
Basic Tuple
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
2. Single Element Tuple
To create a tuple with a single element, you must include a comma after the element.
t1 = (5) # Not a tuple, just an integer
t2 = (5,) # Correct single-element tuple
print(type(t1)) # <class 'int'>
print(type(t2)) # <class 'tuple'>
3. Tuple with Different Data Types
Tuples can contain mixed data types:
mixed = (1, "Hello", 3.14, True)
print(mixed) # (1, 'Hello', 3.14, True)
4. Nested Tuple (Tuple inside Tuple)
nested = (1, (2, 3), (4, 5))
print(nested[1]) # Output: (2, 3)
print(nested[1][0]) # Output: 2
5. Tuple Packing and Unpacking
Packing
person = ("Alice", 30, "Developer") # Packing tuple
Unpacking
name, age, job = person
print(name) # Alice
print(age) # 30
print(job) # Developer
6. Accessing Tuple Elements
Using indexing:
t = (10, 20, 30)
print(t[1]) # Output: 20
Using slicing:
print(t[0:2]) # Output: (10, 20)
7. Immutability of Tuples
You cannot change elements in a tuple:
t = (1, 2, 3)
# t[0] = 10 # Error: TypeError
8. Tuple Methods
Tuples have two built-in methods:
count(value)
– Returns the number of times a value appears
index(value)
– Returns the index of the first occurrence
t = (1, 2, 2, 3)
print(t.count(2)) # Output: 2
print(t.index(3)) # Output: 3
9. Why Use Tuples?
- Immutability protects data from being changed accidentally
- Slightly faster than lists
- Can be used as dictionary keys or set elements (only if they contain hashable values)
my_dict = {("x", 1): "value"}
print(my_dict[("x", 1)]) # Output: value
10. Tuple vs List (Quick Comparison)
Feature |
Tuple |
List |
Syntax |
(1, 2, 3) |
[1, 2, 3] |
Mutability |
Immutable |
Mutable |
Speed |
Faster |
Slower |
Methods |
Fewer |
More |
Use Case |
Fixed data |
Dynamic data |