Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
