Given a list of elements p, the task is to convert the whole list into a list of sets.
Examples:
Input: p = ['apple', 'banana', 'cherry']
Output: [{‘apple’}, {‘banana’}, {‘cherry’}]
Explanation : Here each element of the list is converted into a set.
Input: p = [1, 2, 3, 4]
Output: [{1}, {2}, {3}, {4}]
Approach :
- Initialize an empty list res to store the converted sets.
- Traverse the given list and for each element of the list, perform the following operations.
- Create an empty set x.
- Add the element of list into the empty set x.
- Append set x to list res.
- Finally return and print list of sets.
# 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 = ['apple', 'banana', 'cherry']
# Printing the final result
print(los(lst))
Output:
[{‘apple’}, {‘banana’}, {‘cherry’}]
Time Complexity: O(N)
