Javaexercise.com

How to Convert List to Set in Python

List and Set both are data structures that are used in Python to collect data. The list stores data in linear order while the set does not maintain any order to store elements. Set mostly is used to store unique elements.

Here, we will discuss the conversion of list elements into a set. Python allows the conversion and the main advantage of this is:

  • To create a set of unique elements

It means when we have a list of elements that may have duplicate elements and if we want to have only unique elements then simply convert the list into a set. We will see several scenarios like:

  • Convert a List to Set
  • Convert Nested List to Set
  • Convert List of Tuples to Set
  • Convert Multiple Lists to Set

Let's get started.

Convert List to Set using Set() Function in Python

Here, we used set() function that returns a set of unique elements after conversion of list to set.

# Create a List
list1 = [12, 23, 42, 58, 5, 12, 36]
print(list1)
# Convert List to Set
set1 = set(list1)
print(set1)

Output:

[12, 23, 42, 58, 5, 12, 36]

{36, 5, 42, 12, 23, 58}

 

Convert Nested List to Set in Python

If we have nested list and try to convert it to a set then python does not allow this because of the list inside a list which is a list that cannot be hashed. This can be solved by converting the internal nested lists to a tuple. We do this in next example.

# Create a List
list1 = [[12, 23], [42, 58, 5, 12, 36]]
print(list1)
# Convert a list to set
set1 = set(list1)
print(set1)

Output:

[[12, 23], [42, 58, 5, 12, 36]]

Traceback (most recent call last):

  File "main.py", line 5, in <module>

    set1 = set(list1)

TypeError: unhashable type: 'list'

 

Convert List of Tuples to Set in Python

In the above example, we faced the issue of conversion nested list to set. Here, we have solution for that by creating a list of tuples that easily can be converted to set. See the Python code.

list1 = [(12, 23), (42, 58, 5, 12, 36)]
print(list1)
set1 = set(list1)
print(set1)

Output:

[(12, 23), (42, 58, 5, 12, 36)]

{(12, 23), (42, 58, 5, 12, 36)}

 

Convert Multiple Lists to Set in Python

This is the scenario when we have multiple lists and want to convert all them into a single set then we can use the below code where we used update() method of set. See the Python code.

list1 = [12, 23, 42, 58, 5, 12, 36]
list2 = [25, 32, 65, 84]
print(list1)
print(list2)
set1 = set()
set1.update(list1,list2)
print(set1)

Output:

[12, 23, 42, 58, 5, 12, 36]

[25, 32, 65, 84]

{32, 65, 36, 5, 42, 12, 84, 23, 25, 58}

 

Note: The update() method of the set is used to add multiple lists into a set.