Python - Convert List of lists to List of Sets

Converting a list of lists to a list of sets is useful for removing duplicates from each inner list while maintaining the outer structure. Python provides several approaches using map(), list comprehensions, and loops.

Using map() Function

The map() function applies the set() constructor to each inner list ?

my_list = [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]

print("The list of lists is:")
print(my_list)

my_result = list(map(set, my_list))

print("The resultant list is:")
print(my_result)
The list of lists is:
[[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]
The resultant list is:
[{2}, {1, 2}, {1, 2, 3}, {1}, {0}]

Using List Comprehension

List comprehension provides a more Pythonic approach ?

my_list = [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]

my_result = [set(inner_list) for inner_list in my_list]

print("Original list:", my_list)
print("Result:", my_result)
Original list: [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]
Result: [{2}, {1, 2}, {1, 2, 3}, {1}, {0}]

Using For Loop

For more complex operations, a traditional loop works well ?

my_list = [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]

my_result = []
for inner_list in my_list:
    my_result.append(set(inner_list))

print("Original list:", my_list)
print("Result:", my_result)
print("Type of first element:", type(my_result[0]))
Original list: [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]
Result: [{2}, {1, 2}, {1, 2, 3}, {1}, {0}]
Type of first element: <class 'set'>

Comparison

Method Readability Performance Best For
map() Good Fast Simple transformations
List Comprehension Excellent Fast Pythonic code
For Loop Good Slower Complex logic

Conclusion

Use list(map(set, my_list)) for quick conversion or list comprehension [set(inner_list) for inner_list in my_list] for more readable code. Both methods effectively remove duplicates from each inner list while preserving the outer structure.

Updated on: 2026-03-26T13:17:59+05:30

888 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements