Python Tuple: Complete Master Notes & 25 Practice Solutions

Master Python Tuples from core definitions, immutability principles, single-element comma rules, packing/unpacking, nested tuples, function returns, to 25 practice questions with complete executable solutions.

1. What is a Tuple in Python?

English Definition

A Tuple is an ordered, immutable collection in Python enclosed in round parentheses (). Tuples allow duplicate elements, support indexing/slicing, and cannot be altered after creation.

Hinglish Explanation

Tuple Python mein ek data structure hai jisme multiple values ek hi variable me store hoti hain. Key rule: Tuple change nahi ho sakta (immutable).

2. Creating Tuples & Syntax Variations

Single Element Comma Rule

Writing num = (10) creates an int integer! To create a single-element tuple, you must include a trailing comma: num = (10,).

Tuple Without Parentheses

Python mein bina round brackets ke bhi numbers separated by commas dene se automatically tuple ban jata hai (Tuple Packing): nums = 10, 20, 30.

Python Code - Creating Tuples
numbers = (10, 20, 30, 40)
empty_tuple = ()
single_elem = (10,)
no_brackets = 10, 20, 30, 40
mixed_data = (10, "Python", 20.5, True)

print("Standard Tuple:", numbers)
print("Single Element Type:", type(single_elem))
print("Without Brackets:", no_brackets)
print("Mixed Tuple:", mixed_data)
Output
Standard Tuple: (10, 20, 30, 40)
Single Element Type: <class 'tuple'>
Without Brackets: (10, 20, 30, 40)
Mixed Tuple: (10, 'Python', 20.5, True)

3. Tuple Indexing & Slicing

Access tuple elements using zero-based indexing tuple[0], negative indexing tuple[-1], or extract sub-tuples using slicing tuple[start:stop:step].

Python Code - Indexing & Slicing
numbers = (10, 20, 30, 40, 50)

print("First element (0):", numbers[0])
print("Last element (-1):", numbers[-1])
print("Slice [1:4]:", numbers[1:4])
print("Step 2 [::2]:", numbers[::2])
print("Reversed [::-1]:", numbers[::-1])
Output
First element (0): 10
Last element (-1): 50
Slice [1:4]: (20, 30, 40)
Step 2 [::2]: (10, 30, 50)
Reversed [::-1]: (50, 40, 30, 20, 10)

4. The Immutability Rule

Attempting to assign a new value to an existing index in a tuple will raise a TypeError.

Python Code - Demonstrating Immutability
numbers = (10, 20, 30)
try:
    numbers[1] = 50
except TypeError as e:
    print("Error caught:", e)
Output
Error caught: 'tuple' object does not support item assignment

5. Looping Through a Tuple

Python Code - Iterating over Tuple
numbers = (10, 20, 30, 40)

print("Direct Loop:")
for item in numbers:
    print("Item:", item)

print("
Range Index Loop:")
for i in range(len(numbers)):
    print("Index", i, ":", numbers[i])
Output
Direct Loop:
Item: 10
Item: 20
Item: 30
Item: 40

Range Index Loop:
Index 0 : 10
Index 1 : 20
Index 2 : 30
Index 3 : 40

6. Tuple Built-in Methods (count & index)

Because tuples are immutable, they only possess two built-in methods: count() and index().

Python Code - count() and index()
numbers = (10, 20, 20, 30, 20, 40)

print("Count of 20:", numbers.count(20))
print("Index of 30:", numbers.index(30))
Output
Count of 20: 3
Index of 30: 3

7. Concatenation, Repetition & Membership

Python Code - Tuple Operations
t1 = (10, 20)
t2 = (30, 40)

combined = t1 + t2
repeated = t1 * 3

print("Concatenated (+):", combined)
print("Repeated (*):", repeated)
print("Is 20 in t1?", 20 in t1)
print("Is 50 not in t1?", 50 not in t1)
Output
Concatenated (+): (10, 20, 30, 40)
Repeated (*): (10, 20, 10, 20, 10, 20)
Is 20 in t1? True
Is 50 not in t1? True

8. Tuple Packing & Advanced Unpacking (* Operator)

Wildcard * Unpacking

Using *var during unpacking collects excess items into a list: a, b, *c = (10, 20, 30, 40, 50).

Hinglish Explanation

Tuple unpacking se tuple ke values ko multiple variables mein ek sath assign kar sakte hain. * operator bachi hui values ko list ke roop mein store kar leta hai.

Python Code - Unpacking Variations
numbers = (10, 20, 30, 40, 50)

a, b, *c = numbers
print("a:", a, "| b:", b, "| c:", c)

first, *middle, last = numbers
print("first:", first, "| middle:", middle, "| last:", last)
Output
a: 10 | b: 20 | c: [30, 40, 50]
first: 10 | middle: [20, 30, 40] | last: 50

9. Nested Tuples & Multi-level Loops

Python Code - Nested Tuple Access
nested = ((10, 20), (30, 40), (50, 60))

print("First inner tuple:", nested[0])
print("Specific element (0, 1):", nested[0][1])

print("
Nested Loop Iteration:")
for row in nested:
    for val in row:
        print(val, end=" ")
    print()
Output
First inner tuple: (10, 20)
Specific element (0, 1): 20

Nested Loop Iteration:
10 20
30 40
50 60

10. Built-in Math & Boolean Functions

Functions like sum(), min(), max(), any(), all(), and sorted() work seamlessly with tuples. Note that sorted() returns a sorted List.

Python Code - Math & Sorting
nums = (50, 20, 40, 10, 30)

print("Sum:", sum(nums))
print("Max:", max(nums))
print("Min:", min(nums))
print("Sorted (returns list):", sorted(nums))
print("Sorted Descending:", sorted(nums, reverse=True))
print("Any True (0, 0, 10):", any((0, 0, 10)))
print("All True (10, 20, 30):", all((10, 20, 30)))
Output
Sum: 150
Max: 50
Min: 10
Sorted (returns list): [10, 20, 30, 40, 50]
Sorted Descending: [50, 40, 30, 20, 10]
Any True (0, 0, 10): True
All True (10, 20, 30): True

11. Type Conversions (to/from Tuple)

Python Code - Converting Data Types
py_list = [10, 20, 30]
tup_from_list = tuple(py_list)

py_str = "Python"
tup_from_str = tuple(py_str)

py_set = {10, 20, 30}
tup_from_set = tuple(py_set)

print("List to Tuple:", tup_from_list)
print("String to Tuple:", tup_from_str)
print("Set to Tuple:", tup_from_set)
Output
List to Tuple: (10, 20, 30)
String to Tuple: ('P', 'y', 't', 'h', 'o', 'n')
Set to Tuple: (10, 20, 30)

12. Advanced Interoperability & Function Returns

Mutable List inside Immutable Tuple

If a tuple contains a list element ([10, 20], [30, 40]), the list itself can be modified in-place data[0][0] = 100 because list objects are mutable.

Tuple as Dictionary Key

Tuples immutable hone ki wajah se hashable hote hain, isliye inko dictionary keys ke roop mein use kiya ja sakta hai: {(101, "Python"): "Gagan"}.

Python Code - Functions Returning Multiple Values
def get_user_info():
    name = "Gagan"
    age = 22
    course = "MCA"
    return name, age, course

result = get_user_info()
print("Function Returned Tuple:", result)

student_dict = {
    (101, "Python"): "Gagan",
    (102, "SQL"): "Rahul"
}
print("Tuple as Dict Key:", student_dict)
Output
Function Returned Tuple: ('Gagan', 22, 'MCA')
Tuple as Dict Key: {(101, 'Python'): 'Gagan', (102, 'SQL'): 'Rahul'}

13. Operations Summary Cheat Sheet

Operation Syntax / Expression Allowed on Tuple?
Access Item tuple[0] Yes
Modify Item tuple[0] = 100 No (TypeError)
Delete Item del tuple[0] No (TypeError)
Delete Entire Tuple del tuple_name Yes
Concatenate tuple1 + tuple2 Yes (Returns new tuple)
Repeat tuple * n Yes (Returns new tuple)
Methods count(), index() Only these 2 built-in methods

14. 25 Tuple Practice Questions

Practice Questions (1 - 25)

1. Find maximum number in a tuple.

2. Find minimum number in a tuple.

3. Find sum of all numbers in a tuple.

4. Find total length of a tuple.

5. Reverse a tuple using slicing.

6. Search if an element exists in a tuple using in.

7. Find frequency of an element using count().

8. Find index position of an element using index().

9. Combine two tuples using + operator.

10. Convert a tuple into a list.

11. Convert a list into a tuple.

12. Sort tuple elements in ascending order using sorted().

13. Sort tuple elements in descending order.

14. Perform tuple unpacking into separate variables.

15. Access a value from a nested tuple.

16. Find duplicate values in a tuple.

17. Extract unique values from a tuple using set conversion.

18. Find the second largest number in a tuple.

19. Find the second smallest number in a tuple.

20. Filter even numbers from a tuple.

21. Filter odd numbers from a tuple.

22. Filter positive numbers from a tuple.

23. Filter negative numbers from a tuple.

24. Create a reversed tuple using reversed().

25. Loop through tuple elements and print each with index.

15. Step-by-Step Python Code Solutions

Python Code - Solutions (Q1 - Q25)
nums = (10, 50, 20, 80, -30, 20, 40)

print("Q1 Max:", max(nums))
print("Q2 Min:", min(nums))
print("Q3 Sum:", sum(nums))
print("Q4 Length:", len(nums))
print("Q5 Reversed:", nums[::-1])

print("Q6 Is 50 in nums?", 50 in nums)
print("Q7 Frequency of 20:", nums.count(20))
print("Q8 Index of 80:", nums.index(80))

t1 = (1, 2)
t2 = (3, 4)
print("Q9 Combined:", t1 + t2)

l_from_t = list(nums)
print("Q10 Tuple to List:", l_from_t)

t_from_l = tuple([100, 200, 300])
print("Q11 List to Tuple:", t_from_l)

print("Q12 Ascending Sort:", sorted(nums))
print("Q13 Descending Sort:", sorted(nums, reverse=True))

a, b, *rest = nums
print("Q14 Unpacked a, b:", a, b)

nested = ((10, 20), (30, 40))
print("Q15 Nested Access (1, 0):", nested[1][0])

unique_vals = tuple(set(nums))
print("Q17 Unique Values:", unique_vals)

sorted_unique = sorted(list(set(nums)))
print("Q18 Second Largest:", sorted_unique[-2])
print("Q19 Second Smallest:", sorted_unique[1])

print("Q20 Evens:", tuple(x for x in nums if x % 2 == 0))
print("Q21 Odds:", tuple(x for x in nums if x % 2 != 0))
print("Q22 Positives:", tuple(x for x in nums if x > 0))
print("Q23 Negatives:", tuple(x for x in nums if x < 0))

rev_tup = tuple(reversed(nums))
print("Q24 Reversed Tuple via reversed():", rev_tup)

print("
Q25 Enumerate Loop:")
for idx, val in enumerate(nums):
    print("  Index", idx, "->", val)
Output
Q1 Max: 80
Q2 Min: -30
Q3 Sum: 190
Q4 Length: 7
Q5 Reversed: (40, 20, -30, 80, 20, 50, 10)
Q6 Is 50 in nums? True
Q7 Frequency of 20: 2
Q8 Index of 80: 3
Q9 Combined: (1, 2, 3, 4)
Q10 Tuple to List: [10, 50, 20, 80, -30, 20, 40]
Q11 List to Tuple: (100, 200, 300)
Q12 Ascending Sort: [-30, 10, 20, 20, 40, 50, 80]
Q13 Descending Sort: [80, 50, 40, 20, 20, 10, -30]
Q14 Unpacked a, b: 10 50
Q15 Nested Access (1, 0): 30
Q18 Second Largest: 50
Q19 Second Smallest: 10
Q20 Evens: (10, 50, 20, 80, -30, 20, 40)
Q21 Odds: ()
Q22 Positives: (10, 50, 20, 80, 20, 40)
Q23 Negatives: (-30,)
Q24 Reversed Tuple via reversed(): (40, 20, -30, 80, 20, 50, 10)

Q25 Enumerate Loop:
Index 0 -> 10
Index 1 -> 50
Index 2 -> 20
Index 3 -> 80
Index 4 -> -30
Index 5 -> 20
Index 6 -> 40