Using Data Structures as Keys in Python Dictionary

Which of the following data structures may be used as keys in a dict?

Strings

Lists

Tuples

Answer:

Strings and tuples can be used as keys in a dict but lists cannot.

In Python, only immutable data structures can be used as keys in a dict, which includes strings and tuples. Lists are mutable and can't be used as keys.

Explanation:

In Python, strings and tuples can be used as keys in a dict but lists cannot. This is because in Python, only immutable items can be used as keys for a dict. Both strings and tuples are examples of immutable data structures in Python. For instance, a string, once created, cannot be changed. On the other hand, lists are mutable, meaning they can be altered after creation, which makes them ineligible to be used as dictionary keys.

This is the main answer to your question. To elaborate, when we say a data structure is mutable, it means it can be changed after it's created, while if it's immutable it cannot be changed. The keys of a dictionary in Python must be immutable because they are hashed. If you could change them, it would mess up the hash table structure that underlies the implementation of the dictionary.

In conclusion, among Strings, Lists, and Tuples, only Strings and Tuples can be used as keys in a dict.

← Exploring the role of analytics in marketing An oak tree s survivorship curve →