Python - Tuple Exercises
Exercise 1: Create a Tuple
Task: Create a tuple with the following values: "apple", "banana", "cherry"
Solution:
fruits = ("apple", "banana", "cherry")
print(fruits)Exercise 2: Access Tuple Items
Task: Print the second item in this tuple: ("red", "green", "blue")
Solution:
colors = ("red", "green", "blue")
print(colors[1])Exercise 3: Check if Item Exists
Task: Check if "banana" is in the tuple: ("apple", "banana", "cherry")
Solution:
fruits = ("apple", "banana", "cherry")
if "banana" in fruits:
print("Yes")
else:
print("No")Exercise 4: Update a Tuple (Workaround)
Task: Replace "green" with "yellow" in this tuple: ("red", "green", "blue")
Solution:
colors = ("red", "green", "blue")
temp = list(colors)
temp[1] = "yellow"
colors = tuple(temp)
print(colors)Exercise 5: Unpack a Tuple
Task: Unpack the tuple ("Tom", 25, "Developer") into name, age, and profession.
Solution:
person = ("Tom", 25, "Developer")
name, age, profession = person
print(name)
print(age)
print(profession)Exercise 6: Loop Through a Tuple
Task: Print all elements of ("Python", "Java", "C++") using a loop.
Solution:
languages = ("Python", "Java", "C++")
for lang in languages:
print(lang)Exercise 7: Join Tuples
Task: Join ("a", "b") and (1, 2) into one tuple.
Solution:
letters = ("a", "b")
numbers = (1, 2)
combined = letters + numbers
print(combined)Exercise 8: Tuple Count Method
Task: Count how many times 5 appears in the tuple (5, 3, 5, 2, 5, 1)
Solution:
data = (5, 3, 5, 2, 5, 1)
print(data.count(5)) # Output: 3Exercise 9: Tuple Index Method
Task: Find the index of "apple" in the tuple ("banana", "apple", "cherry")
Solution:
fruits = ("banana", "apple", "cherry")
print(fruits.index("apple")) # Output: 1Exercise 10: Nested Tuple Unpacking
Task: Given ("John", (90, 95, 100)), unpack it into name, marks1, marks2, marks3.
Solution:
student = ("John", (90, 95, 100))
name, (m1, m2, m3) = student
print(name)
print(m1, m2, m3)Bonus Challenge: Tuple Comprehension Workaround
Task: Tuples don’t support comprehension directly, but how can you create a tuple of squares from 1 to 5?
Solution:
squares = tuple(x**2 for x in range(1, 6))
print(squares) # Output: (1, 4, 9, 16, 25)