Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Convert List of lists to list of Sets

  • Last Updated : 25 Feb, 2021

Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets.

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
Output : [{1, 2}, {1, 2, 3}, {2}, {0}]

Input : [[4, 4], [5, 5, 5], [1, 2, 3]]
Output : [{4}, {5}, {1, 2, 3}]

Method 1: Using list comprehension



This can easily be achieved using list comprehension. We just iterate through each list converting the lists to the sets.

Python3




# python3 program to convert list
# of lists to a list of sets
  
  
# initializing list
test_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
  
# printing original list
print("The original list of lists : " + str(test_list))
  
# using list comprehension
# convert list of lists to list of sets
res = [set(ele) for ele in test_list]
  
# print result
print("The converted list of sets : " + str(res))

Output:

he original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]

Method 2 : Using map() + set

We can use the combination of map function and set operator to perform this particular task. The map function binds each list and converts it into the set.

Python3




# Python3 code to demonstrate
# convert list of lists to list of sets
# using map() + set
  
# initializing list
test_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
  
# printing original list
print("The original list of lists : " + str(test_list))
  
# using map() + set
res = list(map(set, test_list))
  
# print result
print("The converted list of sets : " + str(res))

Output:

The original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]



My Personal Notes arrow_drop_up
Recommended Articles
Page :