Given a set of elements p, the task is to write a Python program to convert the whole set into a list of Python Sets.
Example:
Input : p = {‘sky’, ‘is’, ‘blue’}
Output : [{‘blue’}, {‘is’}, {‘sky’}]
Explanation : Here each element of the set is converted into a individual set.
Input : p = {10, 20, 30, 40}
Output : [{10}, {20}, {30}, {40}]
Breaking a Set into a List of Sets Naive Approach
Here we have used a for-loop to iterate on all elements of the Set and create a new set for each item and append to the new list.
def los(l):
res = []
for i in l:
# creating an empty set
x = set ()
x.add(i)
res.append(x)
# returning final list of sets
return (res)
# Driver code lst = { 'sky' , 'is' , 'blue' }
# Printing the final result print (los(lst))
|
Output:
[{'sky'}, {'is'}, {'blue'}]
Breaking a Set into a List of Sets Using Python map() and lambda function
Here we have used lambda function and Python map() function to create a new set for each set item and create a list from it.
set1 = { 1 , 9 , 8 , 6 , 5 }
los = list ( map ( lambda x: {x}, set1))
print ( "List of set:" , los)
|
Output:
List of set: [{1}, {5}, {6}, {8}, {9}]
Breaking a Set into a List of Sets Using List comprehension
Here we are using list comprehension and inside the list comprehension block, we are creating a new set. Thus, the result of the list comprehension will give a list of sets.
set1 = { 1 , 9 , 8 , 6 , 5 }
los = [{elem} for elem in set1]
print ( "List of set:" , los)
|
Output:
List of set: [{1}, {5}, {6}, {8}, {9}]