Which collection is immutable by design in Python?

Prepare for the TJR Bootcamp Test with flashcards and detailed questions. Get hints and explanations for each query. Ace your exam!

Multiple Choice

Which collection is immutable by design in Python?

Mutability refers to whether a container allows its contents to be changed after it’s created. The collection designed to be immutable in Python is the tuple. Once a tuple is created, you can’t assign to an index, append, or remove elements from it. Any attempt to modify it in place will raise an error, for example trying to change t[0] in a tuple t will fail. You can, however, create a new tuple from the existing one (like through concatenation or slicing), but the original remains unchanged.

This immutability is what lets tuples be used as keys in dictionaries or as elements in sets, provided all their contained items are hashable. By contrast, lists, dictionaries, and sets are mutable: you can add, remove, or alter their elements in place, which is why they aren’t immutable by design. Note that a tuple can contain a mutable object (like a list) inside it, and that inner object can still be changed, but the tuple’s own structure and bindings cannot be altered.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy