Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have:
a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The output should be:
[{1, 2}, {1, 2, 3}, {2}, {0}]
Let's explore some method's to achieve this.
Using List Comprehension
This method uses a one-liner loop that converts each sublist into a set using the set() constructor inside a list comprehension.
a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
# list comprehension
b = [set(x) for x in a]
print(b)
Output
[{1, 2}, {1, 2, 3}, {2}, {0}]
Explanation:
- We loop through each sublist x in a using list comprehension.
- Each x is converted into a set using set(x) to remove duplicates.
Using map() and set
We use the map() function to apply set() to every sublist in the input list and then convert the result to a list.
a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
b = list(map(set, a))
print(b)
Output
[{1, 2}, {1, 2, 3}, {2}, {0}]
Explanation:
- map(set, a) applies the set function to each element of a.
- The result is a map object which is then converted into a list using list().
Using a for Loop and set()
We use a traditional for loop to iterate over each sublist and append the converted set to a new list.
a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
b = []
for x in a:
b.append(set(x))
print(b)
Output
[{1, 2, 3}, {4, 5, 6}, {8, 9, 7}]
Explanation:
- We initialize an empty list b.
- For each sublist x, we convert it into a set and append it to b.