Creating a List of Sets in Python
Below are some of the ways by which we can create a list of sets in Python:
- Iterative Approach
- Using List Comprehension
- Using map() Function
Create a List of Sets Using an Iterative Approach
In this example, the below code demonstrates an iterative approach to creating a list of sets in Python. It uses a loop to iterate through a specified range, where each iteration generates a new set containing consecutive integers
Python3
# Iterative Approach array_of_sets = [] for i in range ( 0 , 10 , 3 ): new_set = set ( range (i, i + 3 )) array_of_sets.append(new_set) print (array_of_sets) |
[{0, 1, 2}, {3, 4, 5}, {8, 6, 7}, {9, 10, 11}]
Create a List of Sets Using List Comprehension
In this example, below code utilizes list comprehension to create an list of sets in Python. It generates sets with consecutive integers using a compact syntax and the specified range. The resulting array of sets is printed using the `print` statement.
Python3
# Using List Comprehension array_of_sets = [ set ( range (i, i + 3 )) for i in range ( 0 , 10 , 3 )] print (array_of_sets) |
[{0, 1, 2}, {3, 4, 5}, {8, 6, 7}, {9, 10, 11}]
Create a List of Sets Using map() Function
In this example, below code employs the map()
function and lambda expression to create an list of sets in Python. The lambda function generates sets with consecutive integers, and the map function applies it to each element in the specified range
Python3
# Using the map() Function array_of_sets = list ( map ( lambda i: set ( range (i, i + 3 )), range ( 0 , 10 , 3 ))) print (array_of_sets) |
[{0, 1, 2}, {3, 4, 5}, {8, 6, 7}, {9, 10, 11}]
Creating a List of Sets in Python
We are given a task to create a list of sets in Python using different approaches. In this article, we will see how to create a list of set using different methods in Python.
Example :
Input : [] Output: [{0, 1, 2}, {3, 4, 5}, {8, 6, 7}, {9, 10, 11}] Explanation: We have given an list and here we are creating list of sets.