Python - Convert List of lists to List of Sets

PythonServer Side ProgrammingProgramming

When it is required to convert a list of list to a list of set, the ‘map’, ‘set’, and ‘list’ methods are used.

Example

Below is a demonstration of the same

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)

Output

The list of lists is:
[[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]]
The resultant list is:
[set([2]), set([1, 2]), set([1, 2, 3]), set([1]), set([0])]

Explanation

  • A list of list is defined and is displayed on the console.

  • The list is converted to a set using the ‘map’ function.

  • This is again converted to a list.

  • This is assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 21-Sep-2021 08:29:02
Advertisements