Convert list to set
In this article, we will take a look at 3 different ways to convert a list to set in python with example code, its output and explanation. At the end, we will also inspect the error TypeError: unhashable type: ‘list’, its cause and reason.

Method 1: Using set() constructor
A set can be created using its constructor which takes an iterable as argument. Iterable means an object that can be iterated.
Since a list can be iterated, it is also an iterable.
So, we can create a set directly from a list using its constructor. Example,

# define a list
numbers = [1, 2, 3, 4]
# convert list to set
s = set(numbers)
# print the type of set
print(type(s))
print(s)

This prints

<class ‘set’>
{1, 2, 3, 4}

The list is converted to a set with all the elements.
Method 2: Using * operator
*(asterisk) or unpacking operator in python which, when placed before a list, unpacks its elements into separate values. These values if enclosed between curly braces becomes a set populated with the elements of the list.
Remember that a set can also be created with curly braces containing optional elements.
Example of this approach follows

#define list
numbers = [1, 2, 3, 4]
# unpack list elements to set
s = {(*numbers)}
print(type(s))
print(s)

Output is

<class ‘set’>
{1, 2, 3, 4}

Method 3: Using for loop
Create an empty set using its constructor or empty curly braces. Iterate over the list using for loop and in every iteration, add the current list element to the set with its add() method. Example,

# define a list
numbers = [1, 2, 3, 4]
# create set
s=set()
# iterate list
for n in numbers:
    s3.add(n)
print(type(s))
print(s)

which prints

<class ‘set’>
{1, 2, 3, 4}

Adding list to set
You might be wondering why don’t we create an empty set and add a list directly to it with add() method as below

# define a list
numbers = [1, 2, 3, 4]
s = {}
# add list to set
s.add(numbers)
print(type(s))
print(s)

Output will be

s = {numbers}
TypeError: unhashable type: ‘list’

The reason is that elements of a set must be hashable.

Hashable
, here means an object whose value never changes or an object which is mutable. A python list is immutable.
Hence, when you try to add a list to a set with add(), the entire list is treated as an element and it throws an error.
Python docs about hashable object state,

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; mutable containers (such as lists or dictionaries) are not;

Note that this is different from the first method where we are passing the list to the set constructor. It expects an iterable and adds its individual elements while with add(), we are trying to add the list and not its individual elements.

Click the clap if you liked the article.