Which of the following is the main reason to use a tuple instead of a list in Python?
Think about performance and memory usage differences between tuples and lists.
Tuples are immutable, which allows Python to optimize their storage and access speed. They use less memory and are faster than lists, which are mutable.
What is the output of this code?
t = (1, 2, 3) t[0] = 10 print(t)
Remember that tuples cannot be changed after creation.
Tuples are immutable, so trying to assign a new value to an element causes a TypeError.
What will be the output of this code?
d = {('a', 1): 'value1', ('b', 2): 'value2'}
print(d[('a', 1)])Think about which data types can be used as dictionary keys.
Tuples are immutable and hashable, so they can be used as dictionary keys. The code prints the value associated with the key ('a', 1).
Why might a programmer prefer tuples over lists to store fixed data like coordinates?
Think about data safety and accidental changes.
Tuples are immutable, so once created, their data cannot be changed. This prevents accidental modification of fixed data.
What is the output of this code?
t = (1, 2, 3, 4, 5) a, *b, c = t print(a, b, c)
Recall how star (*) unpacks multiple elements into a list.
The star expression collects all middle elements into a list. So a=1, b=[2,3,4], c=5.