TypeError: unhashable type: ‘list’ when using built-in set function [Fixed]

TypeError: unhashable type: 'list'

The error message TypeError: unhashable type: 'list' typically occurs when you’re trying to use a list as a key in a dictionary or as an element in a set. Lists are mutable objects in Python, which means their contents can be changed after they are created. As a consequence, they are unhashable and cannot be used as keys in dictionaries or elements in sets because these data structures require their elements to be hashable.

For example, you might encounter this error if you try to create a set with a list as one of its elements:

Python
my_set = set([1, 2, [3, 4]])  # This will raise a TypeError

To fix this issue, you can convert the list to a tuple, as tuples are immutable and hashable:

Python
my_set = set([1, 2, tuple([3, 4])])

Or simply use a tuple from the start:

Python
my_set = {(1, 2), (3, 4)}  # Using tuples instead of lists

If you’re encountering this error with the built-in set() function, it’s likely because you’re passing a list (or another unhashable type) as an element when creating the set. Make sure that all elements passed to the set function are hashable, such as integers, strings, or tuples, rather than lists.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart