Tuples in Python are fundamental data structure that function as immutable sequences. They are used to store multiple items in a single variable and can contain elements of different types. Here we present 15 multiple-choice questions to test your knowledge of Python Tuples. Each MCQ has the correct answer with an explanation.
1. How is a tuple with a single element defined in Python?
Answer:
Explanation:
In Python, a single element tuple must have a comma after the item, otherwise, it's not recognized as a tuple.
2. How do you access the second element of a tuple 'my_tuple'?
Answer:
Explanation:
Tuple indices start at 0. So the second element is accessed using my_tuple[1].
3. Which of the following is true about modifying tuples?
Answer:
Explanation:
Tuples are immutable in Python, meaning their size and the values of elements cannot be changed.
4. How do you unpack the values of a tuple 't' into variables a, b, and c?
Answer:
Explanation:
The syntax a, b, c = t automatically unpacks the values of tuple 't' into variables a, b, and c.
5. How do you loop through a tuple named 'my_tuple' to print each value?
Answer:
Explanation:
Both methods are valid. You can loop directly through the tuple items or loop through the tuple indices.
6. How do you concatenate tuple1 and tuple2 in Python?
Answer:
Explanation:
The + operator is used to concatenate tuples in Python.
7. Which method would you use to count the occurrences of an element in a tuple?
Answer:
Explanation:
The count() method returns the number of times an element appears in a tuple.
8. What is the output of ('Hi!') * 4 in Python?
Answer:
Explanation:
Multiplying a string by an integer n concatenates the string n times.
9. How do you convert a list [1, 2, 3] to a tuple in Python?
Answer:
Explanation:
The tuple() function is used to convert a list to a tuple.
10. What is the result of ('a', 'b') < ('c', 'd') in Python?
Answer:
Explanation:
Tuple comparison is performed element by element. 'a' is less than 'c', so the expression is True.
11. What does my_tuple.index('a') return if my_tuple = ('a', 'b', 'a')?
Answer:
Explanation:
The index() method returns the index of the first occurrence of the value.
12. What does len(('a', 'b', 'c')) return?
Answer:
Explanation:
len() returns the number of elements in the tuple.
13. How do you create a nested tuple?
Answer:
Explanation:
Nested tuples are created by placing tuples inside another tuple.
14. What will ('Hello',) * 2 produce?
Answer:
Explanation:
Multiplying a tuple by an integer n repeats the tuple n times.
15. What is the output of the following code?
t = (1, 2, [3, 4])
t[2][0] = 'x'
print(t)
Answer:
Explanation:
While tuples are immutable, their mutable elements (like lists) can be modified.