Python – Convert List of lists to list of Sets
Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets.
Examples:
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 listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint("The original list of lists : " + str(test_list)) # using list comprehension# convert list of lists to list of setsres = [set(ele) for ele in test_list] # print resultprint("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}]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 listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint("The original list of lists : " + str(test_list)) # using map() + setres = list(map(set, test_list)) # print resultprint("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}]


.png)