I was studying the difference between lists and tuples (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.
A sentence in the article got me:
Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.
I have a hard time thinking of a situation where I would like to use a tuple as a dictionary key. Can you provide an example problem where this would be the natural, efficient, elegant, or obvious solution?
Edit:
Thanks for your examples. So far I take that a very important application is the caching of function values.
To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.
Literals and immutable types like numbers, strings, and tuples are all hashable, and can therefore serve as keys in dictionaries.
Classic Example: You want to store point value as tuple of (x, y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With