Skip to content

Python Hashable list

  • by

In Python, a hashable object is an object that can be used as a key in a dictionary or as an element in a set. Hashable objects are immutable, meaning they cannot be changed after they are created.

A list in Python is not hashable because it is mutable. If you try to use a list as a key in a dictionary or as an element in a set, you will get a TypeError stating that lists are unhashable.

However, if you need to use a list-like object that is hashable, you can use a tuple instead. Tuples are similar to lists, but they are immutable and therefore hashable. Here’s an example:

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

print(my_tuple) 

my_dict = {my_tuple: "value"}
print(my_dict)

Output:

Python Hashable list

In the example above, we converted the list my_list into a tuple my_tuple, which is then used as a key in the dictionary my_dict.

By using tuples instead of lists, you can have hashable objects that preserve the order and values of the original list, while being able to use them as keys or elements in data structures that require hashable objects.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading