Tuples
Prerequisites: Variables, data types, operators, loops, lists
1. What is a Tuple?
A tuple is an ordered, immutable collection of items. Think of it as a list that cannot be changed after creation.
# A tuple looks like a list but uses parentheses
t = (1, 2, 3, 4, 5)
2. Creating Tuples
2.1 Using Parentheses
empty =
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
print(numbers)
print(type(numbers))
Output:
(1, 2, 3, 4, 5)
<class 'tuple'>
2.2 Single Element Tuple, IMPORTANT
# WRONG -- this is just an integer, NOT a tuple
t1 = (5)
print(type(t1)) # <class 'int'>
# CORRECT -- need a trailing comma
t2 = (5,)
print(type(t2)) # <class 'tuple'>
# Also correct without parentheses
t3 = 5,
print(type(t3)) # <class 'tuple'>
Output:
<class 'int'>
<class 'tuple'>
<class 'tuple'>
Remember: A single-element tuple needs a trailing comma. (5) is just 5 in parentheses.
2.3 Without Parentheses (tuple packing)
t = 1, 2, 3, 4, 5
print(t)
print(type(t))
Output:
(1, 2, 3, 4, 5)
<class 'tuple'>
2.4 Using tuple Function
# Convert list to tuple
t1 = tuple([1, 2, 3])
print(t1)
# Convert string to tuple
t2 = tuple("Hello")
print(t2)
# Convert range to tuple
t3 = tuple(range(1, 6))
print(t3)
Output:
(1, 2, 3)
('H', 'e', 'l', 'l', 'o')
(1, 2, 3, 4, 5)
3. Indexing
Works exactly like lists and strings.
3.1 Positive Indexing
t = (10, 20, 30, 40, 50)
print(t[0]) # 10
print(t[2]) # 30
print(t[4]) # 50
Output:
10
30
50
3.2 Negative Indexing
t = (10, 20, 30, 40, 50)
print(t[-1]) # 50
print(t[-3]) # 30
print(t[-5]) # 10
Output:
50
30
10
4. Slicing
Works exactly like lists and strings: t[start:stop:step]
t = (10, 20, 30, 40, 50, 60, 70)
print(t[2:5]) # (30, 40, 50)
print(t[:3]) # (10, 20, 30)
print(t[3:]) # (40, 50, 60, 70)
print(t[::2]) # (10, 30, 50, 70)
print(t[::-1]) # (70, 60, 50, 40, 30, 20, 10)
Output:
(30, 40, 50)
(10, 20, 30)
(40, 50, 60, 70)
(10, 30, 50, 70)
(70, 60, 50, 40, 30, 20, 10)
Note: Slicing a tuple always returns a new tuple.
5. Tuple Operations
5.1 Concatenation (+)
t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = t1 + t2
print(t3)
Output:
(1, 2, 3, 4, 5, 6)
5.2 Repetition (*)
t = (1, 2) * 3
print(t)
Output:
(1, 2, 1, 2, 1, 2)
5.3 Membership (in / not in)
t = (10, 20, 30, 40, 50)
print(30 in t) # True
print(35 in t) # False
print(100 not in t) # True
Output:
True
False
True
6. Tuples are IMMUTABLE
You cannot change, add, or remove elements from a tuple after creation.
t = (10, 20, 30)
# All of these will cause errors:
# t[0] = 99 # TypeError: 'tuple' object does not support item assignment
# t.append(40) # AttributeError: 'tuple' object has no attribute 'append'
# del t[0] # TypeError: 'tuple' object doesn't support item deletion
But you can:
# Reassign the entire variable to a new tuple
t = (10, 20, 30)
t = t + (40, 50) # creates a NEW tuple
print(t)
Output:
(10, 20, 30, 40, 50)
Caution, mutable elements inside a tuple:
# A tuple can contain a mutable object (like a list)
t = (1, 2, [3, 4])
t[2][0] = 99 # this is allowed! (modifying the list, not the tuple)
print(t)
Output:
(1, 2, [99, 4])
7. Tuple Assignment / Unpacking
One of the most useful features of tuples.
7.1 Basic Unpacking
t = (1, 2, 3)
a, b, c = t
print(a) # 1
print(b) # 2
print(c) # 3
Output:
1
2
3
7.2 Swap Two Variables
a = 10
b = 20
a, b = b, a # tuple unpacking swap
print(a, b)
Output:
20 10
7.3 Multiple Assignment
x, y, z = 10, 20, 30
print(x, y, z)
Output:
10 20 30
7.4 Function Returning Multiple Values
def min_max(L):
return min(L), max(L) # returns a tuple
result = min_max([3, 1, 4, 1, 5])
print(result) # (1, 5)
lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi) # 1 5
Output:
(1, 5)
1 5
8. Nested Tuples
t = ((1, 2), (3, 4), (5, 6))
print(t[0]) # (1, 2)
print(t[1][1]) # 4
print(t[2][0]) # 5
# Traversing nested tuple
for pair in t:
print(pair[0], pair[1])
Output:
(1, 2)
4
5
1 2
3 4
5 6
9. Tuple Methods
Tuples have only two methods (because they are immutable):
9.1 count, Count occurrences of an element
Syntax: tuple.count(element)
t = (1, 2, 3, 2, 4, 2, 5)
print(t.count(2))
print(t.count(9))
Output:
3
0
9.2 index, Find position of first occurrence
Syntax: tuple.index(element[, start[, end]])
t = (10, 20, 30, 20, 40)
print(t.index(20)) # 1
print(t.index(20, 2)) # 3 (search from index 2)
# print(t.index(99)) # ValueError
Output:
1
3
10. Built-in Functions with Tuples
t = (30, 10, 50, 20, 40)
print(len(t)) # 5
print(min(t)) # 10
print(max(t)) # 50
print(sum(t)) # 150
print(sorted(t)) # [10, 20, 30, 40, 50] -- returns a LIST
print(tuple(sorted(t))) # (10, 20, 30, 40, 50) -- convert back to tuple
Output:
5
10
50
150
[10, 20, 30, 40, 50]
(10, 20, 30, 40, 50)
Note: sorted always returns a list, even when given a tuple. Use tuple(sorted(t)) to get a tuple.
11. Tuple vs List Comparison Table
| Feature | Tuple | List |
|---|---|---|
| Syntax | (1, 2, 3) |
[1, 2, 3] |
| Mutable? | No | Yes |
| Methods | count, index |
Many (append, sort, etc.) |
| Speed | Faster | Slower |
| Memory | Uses less | Uses more |
| Can be dict key? | Yes | No |
| Can be set element? | Yes | No |
| Use when | Data should not change | Data needs to change |
12. When to Use Tuple vs List
Use tuples when:
- Data should not be modified (e.g., days of week, RGB colors), Returning multiple values from a function, Using as dictionary keys, You want slightly better performance
# Good uses of tuples
DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
color = (255, 128, 0)
coordinates = (28.6139, 77.2090)
# Dictionary with tuple keys
distances = {
("Delhi", "Mumbai"): 1400,
("Delhi", "Chennai"): 2200,
}
Use lists when:
- Data needs to be modified (add, remove, sort), Collecting user input, Building results incrementally
13. Practice Programs
Program 1: Find min, max, mean of tuple
t = eval(input("Enter a tuple: "))
print("Minimum:", min(t))
print("Maximum:", max(t))
print("Mean:", sum(t) / len(t))
Sample Run:
Enter a tuple: (10, 20, 30, 40, 50)
Minimum: 10
Maximum: 50
Mean: 30.0
Without built-in functions:
t = eval(input("Enter a tuple: "))
minimum = maximum = t[0]
total = 0
for item in t:
if item < minimum:
minimum = item
if item > maximum:
maximum = item
total += item
print("Minimum:", minimum)
print("Maximum:", maximum)
print("Mean:", total / len(t))
Program 2: Linear search in tuple
t = eval(input("Enter a tuple: "))
item = int(input("Enter element to search: "))
found = False
for i in range(len(t)):
if t[i] == item:
print(f"Element {item} found at index {i}")
found = True
break
if not found:
print(f"Element {item} not found")
Sample Run:
Enter a tuple: (10, 20, 30, 40, 50)
Enter element to search: 30
Element 30 found at index 2
Program 3: Count frequency of elements
t = eval(input("Enter a tuple: "))
checked =
for item in t:
if item not in checked:
print(f"{item} appears {t.count(item)} time(s)")
checked = checked + (item,)
Sample Run:
Enter a tuple: (1, 2, 3, 2, 1, 3, 3)
1 appears 2 time(s)
2 appears 2 time(s)
3 appears 3 time(s)
Program 4: Convert list to tuple and vice versa
# List to Tuple
L = [1, 2, 3, 4, 5]
t = tuple(L)
print("List:", L)
print("Converted to tuple:", t)
print("Type:", type(t))
# Tuple to List
t2 = (10, 20, 30)
L2 = list(t2)
print("\nTuple:", t2)
print("Converted to list:", L2)
print("Type:", type(L2))
Output:
List: [1, 2, 3, 4, 5]
Converted to tuple: (1, 2, 3, 4, 5)
Type: <class 'tuple'>
Tuple: (10, 20, 30)
Converted to list: [10, 20, 30]
Type: <class 'list'>
Program 5: Swap two variables using tuple unpacking
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a
print(f"After swap: a = {a}, b = {b}")
Sample Run:
Enter first number: 10
Enter second number: 20
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
Program 6: Sort a tuple (using sorted)
t = eval(input("Enter a tuple: "))
# sorted returns a list, convert back to tuple
ascending = tuple(sorted(t))
descending = tuple(sorted(t, reverse=True))
print("Original:", t)
print("Ascending:", ascending)
print("Descending:", descending)
Sample Run:
Enter a tuple: (30, 10, 50, 20, 40)
Original: (30, 10, 50, 20, 40)
Ascending: (10, 20, 30, 40, 50)
Descending: (50, 40, 30, 20, 10)
14. Common Mistakes
| Mistake | Why it is wrong | Correct way |
|---|---|---|
t = (5) for single element tuple |
This is just int 5 |
t = (5,) with trailing comma |
t[0] = 99 |
Tuples are immutable | Create a new tuple |
t.append(6) |
Tuples have no append |
Convert to list, modify, convert back |
t.sort |
Tuples have no sort |
Use sorted(t) which returns a list |
Forgetting sorted returns a list |
You might expect a tuple | Use tuple(sorted(t)) |
a, b = (1, 2, 3) |
Too many values to unpack | Number of variables must match elements |
$1$2 Quick Tips
-
Single-element tuple is tested almost every year. Remember:
(5,)is a tuple,(5)is just an integer. -
Tuple vs List comparison is a standard 2-3 mark question. Memorize the comparison table.
-
Tuple unpacking (
a, b = b, afor swapping) is a favorite exam question. -
Tuples have only two methods:
countandindex. This is often asked in MCQs. -
"Why are tuples faster than lists?", Because they are immutable, Python can optimize their storage and access.
-
"Can a tuple be a dictionary key?", Yes, because tuples are immutable (and hashable). Lists cannot be dictionary keys.
-
sortedon a tuple returns a list. This is a common trap in exams. -
Tuples with mutable elements: A tuple containing a list like
(1, [2, 3]), the list inside can be modified but the tuple itself cannot. This is an advanced concept sometimes tested in XII.
Prefer watching over reading?
Subscribe for free.