5. Why can a tuple of strings be used as a dictionary key while a list cannot?
- Tuples are faster
- Tuples are immutable and hashable; lists are mutable and unhashable
- Lists cannot hold strings
- Dictionaries only accept tuples
Show answer
Answer: Tuples are immutable and hashable; lists are mutable and unhashable
Keys must be hashable, and their hash must not change.
Lesson: Tuples, namedtuple and dataclasses
6. Why is "".join(parts) preferred over repeated += for building a long string?
- Strings are immutable, so repeated += may copy the growing string each time, while join computes the size once
- join sorts the parts
- join is the only way to concatenate
- It uses less Unicode
Show answer
Answer: Strings are immutable, so repeated += may copy the growing string each time, while join computes the size once
join allocates the result once and copies each part once.
Lesson: Strings, Bytes and Efficient Text Building