Convert the whole list into a list of sets in Python

By | November 23, 2024

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 :

  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.
# 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)

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.