List and tuples are the most important parts of Python data types. In this article, I will share some exercises with answers to practice tuples in Python.
For each exercise, I will provide questions with answer codes. First, try to solve those questions by yourself. If you are not able to solve those on your own, then only see the code.
Table of Contents
- E1: Creating Tuples
- E2: Accessing Elements in a Tuple
- E3: Tuple Concatenation
- E4: Tuple Methods
- E5: Tuple Unpacking
- E6: Immutable Nature of Tuples
- E7: Tuple Slicing
- E8: Checking Membership in a Tuple
- E9: Iterating Through a Tuple
- E10: Tuple Comparison
- E11: Tuple Sorting
- E12: Tuple Repetition
- E13: Tuple Nesting
- E14: Tuple Zip Operation
- E15: Tuple Memory Efficiency
- Conclusion
E1: Creating Tuples
Question: Create a tuple named fruits
containing your favorite fruits.
fruits = ("apple", "banana", "orange")
print(fruits)
Output:
('apple', 'banana', 'orange')
E2: Accessing Elements in a Tuple
Question: Access the second element of the fruits tuple created in the first Python exercises.
fruits = ("apple", "banana", "orange")
print(fruits[1]) # Output: banana
Here, we are accessing the second element of the fruits
tuple using square brackets and the index [1]
. Remember, indexing in Python starts from 0. So [1]
refers to the second element.
E3: Tuple Concatenation
Question: Concatenate the fruits
tuple with another tuple named more_fruits
.
fruits = ("apple", "banana", "orange")
more_fruits = ("grape", "kiwi")
all_fruits = fruits + more_fruits
print(all_fruits)
Output:
('apple', 'banana', 'orange', 'grape', 'kiwi')
We concatenate two tuples fruits and more_fruits using the + operator in this Python exercises. This creates a new tuple all_fruits
containing all the elements from both tuples.
E4: Tuple Methods
Question 1: Count the number of occurrences of “apple” in the all_fruits tuple which we created in the previous Python exercises.
Question 2: Find the index of “orange” in the all_fruits
tuple.
all_fruits = ('apple', 'banana', 'orange', 'grape', 'kiwi')
# Solution for Question 1
print(all_fruits.count("apple"))
# Solution for Question 2
print(all_fruits.index("orange"))
Output:
1
2
Here, we’re utilizing two important tuple methods.
count()
returns the number of occurrences of a specified element in the tuple.index()
returns the index of the first occurrence of a specified element in the tuple.
E5: Tuple Unpacking
Question: Unpack the fruits
tuple into individual variables named a
, b
, and c
.
fruits = ("apple", "banana", "orange")
a, b, c = fruits
print(a)
print(b)
print(c)
Output:
apple
banana
orange
Tuple unpacking allows us to assign the elements of a tuple to individual variables. In this Python exercises, we are unpacking the fruits tuple into variables a, b, and c, respectively.
E6: Immutable Nature of Tuples
Question: Attempt to change the first element of the fruits
tuple to “mango” (will result in an error).
fruits = ("apple", "banana", "orange")
fruits[0] = "mango"
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-3e0fa3eeeb59> in <module>()
----> 1 fruits[0] = "mango"
TypeError: 'tuple' object does not support item assignment
Tuples are immutable, meaning once they are created, their elements cannot be changed. This is the reason, while we are trying to modify a tuple element it is giving an error.
E7: Tuple Slicing
Question: Create a tuple named numbers
containing integers from 1 to 10. Slice the tuple to extract the elements from index 2 to index 6 (inclusive).
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sliced_numbers = numbers[2:7]
print(sliced_numbers)
Output:
(3, 4, 5, 6, 7)
In this exercise, we are using tuple slicing to extract a subset of elements from the numbers
tuple. Slicing syntax follows the pattern [start_index:stop_index+1]
, where start_index
is inclusive and stop_index
is exclusive. So, [2:7]
extracts elements from index 2 to index 6.
E8: Checking Membership in a Tuple
Question: In this Python exercises, check if the element “apple” exists in the all_fruits tuple.
all_fruits = ('apple', 'banana', 'orange', 'grape', 'kiwi')
print("apple" in all_fruits) #Output: True
We can use the in
operator to check if an element exists in a tuple. It returns True
if the element is found, otherwise False
.
E9: Iterating Through a Tuple
Question: Iterate through the numbers
tuple and print each element multiplied by 2.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for num in numbers:
print(num * 2)
Output:
2
4
6
8
10
12
14
16
18
20
We can iterate through a tuple using a for loop. In this Python exercises, we’re iterating through the numbers tuple and printing each element multiplied by 2.
E10: Tuple Comparison
Question: Compare two tuples, tuple1
and tuple2
, to check if they are equal.
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)
print(tuple1 == tuple2) # Output: True
Tuples can be compared for equality using the ==
operator. It returns True
if the elements in both tuples are the same, otherwise False
.
E11: Tuple Sorting
Question: Sort the numbers
tuple in ascending order and print the sorted tuple.
numbers = (10, 17, 9, 23, 7, 12)
sorted_numbers = sorted(numbers)
print(sorted_numbers)
Output:
[7, 9, 10, 12, 17, 23]
The sorted()
function sorts the elements of a tuple and returns a new sorted list. In this Python exercises, we are sorting the numbers tuple and printing the sorted result.
E12: Tuple Repetition
Question: Create a tuple named repeated_tuple
containing the string “Hello” repeated 3 times.
repeated_tuple = ("Hello",) * 3
print(repeated_tuple)
Output:
('Hello', 'Hello', 'Hello')
Using the *
operator with a tuple allows us to repeat its elements a specified number of times. In this exercise, we’re creating a tuple repeated_tuple
containing “Hello” repeated three times.
E13: Tuple Nesting
Question: Create a tuple named nested_tuple
containing two tuples: tuple1
with elements (1, 2, 3) and tuple2
with elements (‘a’, ‘b’, ‘c’).
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
nested_tuple = (tuple1, tuple2)
print(nested_tuple)
Output:
((1, 2, 3), ('a', 'b', 'c'))
Tuples can contain other tuples. In this exercise, we are nesting two tuples tuple1
and tuple2
within another tuple named nested_tuple
.
E14: Tuple Zip Operation
Question: Create two tuples names
and ages
containing names and ages of individuals. Zip these tuples to create a new tuple person_info
containing pairs of (name, age).
names = ("Alice", "Bob", "Charlie")
ages = (25, 30, 35)
person_info = tuple(zip(names, ages))
print(person_info)
Output:
(('Alice', 25), ('Bob', 30), ('Charlie', 35))
The zip()
function is used to combine multiple sequences into a single sequence of tuples. In this Python exercises, we are using zip() to combine names and ages tuples into a new tuple person_info.
E15: Tuple Memory Efficiency
Question: Compare the memory usage of a tuple and a list containing the same elements using the sys.getsizeof()
function.
import sys
tuple_size = sys.getsizeof((1, 2, 3, 4, 5))
list_size = sys.getsizeof([1, 2, 3, 4, 5])
print("Size of tuple:", tuple_size, "bytes")
print("Size of list:", list_size, "bytes")
Output:
Size of tuple: 88 bytes
Size of list: 104 bytes
Tuples are more memory efficient compared to lists. In this exercise, we’re using the sys.getsizeof()
function to compare the memory usage of a tuple and a list containing the same elements.
Conclusion
In this article, I shared some tuple exercises answers, solutions, and example codes which are suitable for beginners to advanced level of Python learners and can be useful before appearing for a job interview. You can download these Python tuple exercises as pdf to practice offline.
This is it for this article. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python. See you in the comment section below.
Similar Read:
Hi there, I’m Anindya Naskar, Data Science Engineer. I created this website to show you what I believe is the best possible way to get your start in the field of Data Science.