Given a list of elements p, the task is to convert the whole list into a list of sets.
Examples :
Input : p = ['red', 'green', 'red']
Output : [{'red'}, {'green'}, {'red'}]
Explanation :
Here each element of the list is converted into a set.
Input : p = [10, 20, 30, 40]
Output : [{10}, {20}, {30}, {40}]
Approach :
1. Initialize an empty list res to store the converted sets.
2. Traverse the given list and for each element of the list, perform the following operations.
3. Create an empty set x.
4. Add the element of list into the empty set x.
5. Append set x to list res.
6. Finally return and print list of sets.
Implementation :
# Python3 program to convert
# list into a list of sets
def los(l):
res = []
# for loop
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 = ['red', 'green', 'red']
# Printing the final result
print(los(lst))
Output :
[{'red'}, {'green'}, {'red'}]
Time Complexity : O(N)
Auxiliary Space : O(1)