Python Tuples: Beginner to Intermediate Practice (Dark Theme)
1. Create a tuple with five numbers and print it
numbers = (10, 20, 30, 40, 50)
print(numbers)
Explanation: Tuples are created using parentheses () . They are immutable. Output:
(10, 20, 30, 40, 50)
2. Create a tuple containing both numbers and strings
mixed = (1, 'Python', 3.5, 'AI')
print(mixed)
Explanation: Tuples can contain different data types. Output: (1, 'Python', 3.5, 'AI')
3. Find the length of a tuple
t = (10, 20, 30, 40)
print(len(t))
Output: 4
4. Access the third element
t = (10, 20, 30, 40, 50)
print(t[2])
Output: 30
5. Slice the tuple (1, 2, 3, 4, 5, 6) to get (3, 4, 5)
1
t = (1, 2, 3, 4, 5, 6)
print(t[2:5])
Output: (3, 4, 5)
6. Check if value exists
t = (10, 20, 30, 40, 50)
print(50 in t)
Output: True
7. Concatenate two tuples
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2)
Output: (1, 2, 3, 4, 5, 6)
8. Repeat a tuple three times
t = (1, 2)
print(t * 3)
Output: (1, 2, 1, 2, 1, 2)
9. Find index of 30
t = (10, 20, 30, 40, 50)
print([Link](30))
Output: 2
2
10. Count occurrences of 2
t = (1, 2, 2, 3, 4, 2)
print([Link](2))
Output: 3
11. Convert a list to tuple
lst = [1, 2, 3, 4]
tuple_from_list = tuple(lst)
print(tuple_from_list)
Output: (1, 2, 3, 4)
12. Convert a tuple to list
t = (5, 6, 7, 8)
lst = list(t)
print(lst)
Output: [5, 6, 7, 8]
13. Unpack tuple into variables
t = (100, 200, 300)
a, b, c = t
print(a, b, c)
Output: 100 200 300
14. Swap two tuples
a = (1, 2)
b = (3, 4)
3
a, b = b, a
print(a, b)
Output: (3, 4) (1, 2)
15. Find max and min
t = (9, 3, 7, 1, 6)
print(max(t), min(t))
Output: 9 1
16. Check equality of tuples
t1 = (1, 2, 3)
t2 = (1, 2, 3)
print(t1 == t2)
Output: True
17. Nested tuple
t = (1, 2, (3, 4))
print(t)
Output: (1, 2, (3, 4))
18. Access inner value 30
t = (10, 20, (25, 30, 35), 40)
print(t[2][1])
Output: 30
19. Sum of all numbers
4
t = (1, 2, 3, 4, 5)
print(sum(t))
Output: 15
20. Join multiple tuples
t1 = (1, 2)
t2 = (3, 4)
t3 = (5, 6)
joined = t1 + t2 + t3
print(joined)
Output: (1, 2, 3, 4, 5, 6)
21. Input n numbers and store in tuple
n = int(input('Enter number of elements: '))
numbers = tuple(int(input()) for _ in range(n))
print(numbers)
Explanation: Uses a loop and tuple comprehension.
22. Reverse a tuple
t = (1, 2, 3, 4, 5)
print(t[::-1])
Output: (5, 4, 3, 2, 1)
23. Check if a tuple is empty
t = ()
print(len(t) == 0)
Output: True
5
24. Create tuple with one element
t = (5,)
print(type(t))
Output: <class 'tuple'>
25. Remove duplicates from a tuple
t = (1, 2, 2, 3, 4, 2)
t = tuple(set(t))
print(t)
Output: (1, 2, 3, 4) — order may vary
End of Tuple Practice (Dark Theme)