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 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}]
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}]
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.