How to Store a List in a Set in Python?

python programs

The set data structure in Python is a mutable container that can only store immutable items (i.e. we can add or remove items to the set object but cannot modify its existing elements).

Because the list is dynamic and mutable, we cannot store or add it to a set in Python.

Why Can’t a Set Contain a List as an Element?

According to the Python documentation, a set can only store hashable objects because data structures such as sets and dictionaries internally use the hash value to access its items.

An object is hashable if it has a hash value which never changes during its lifetime. Most of Python’s immutable built-in objects are hashable.

The list is a mutable container, therefore is not hashable.

Whereas, immutable containers such as tuples and dictionaries are hashable, as long as they only contain hashable items.

Alternative of adding a List to a Set

If we need to store a group of items into a set as a single element, we can do it using a tuple.

>>> s = {1, 2, 3}
>>> t = ('a', 'b', 'c')
>>> s.add(t)
{1, 2, 3, ('a', 'b', 'c')}

Here, all the items in the tuple are immutable. If we try to add a tuple that contains a list, the set.add() method will result in an error.

>>> s = {1, 2, 3}
>>> t = ('a', 'b', ['c', 'd'])
>>> s.add(t)
TypeError: unhashable type: 'list'

It is because on adding a mutable list to a tuple, the tuple object loses its hashability.

In summary, we cannot store or append a list to a set object in Python. If we need to store a group of items as a single element in the set, we should use a tuple, provided that all the items in the tuple are immutable.

Leave a Reply

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