How To Convert List Of List To Set In Python

In this tutorial, we will learn how to convert a list of lists to a set in Python. A set is an unordered collection of unique elements and is commonly used to remove duplicates and perform mathematical operations such as union, intersection, difference, and more.

We’ll be using a few Python built-in functions like chain() and set() to achieve our goal. Let’s get started!

Step 1: Import the necessary libraries

First, we need to import the necessary library called itertools. We’ll be using the chain() function from this library.

Step 2: Create a list of lists

Next, create a list of lists that you want to convert to a set. For example:

Step 3: Flatten the list of lists using itertools.chain()

The itertools.chain() function takes multiple arguments and returns an iterator that produces the elements of the given iterable objects one after the other. We can use this function to flatten our list of lists into a single iterable.

Now, the flattened_list contains all the elements of the original list of lists:

[1, 2, 3, 2, 3, 4, 5, 7, 8, 9, 6, 2, 8, 9]

Step 4: Convert the flattened list to a set

Use Python’s built-in set() function to convert the flattened list to a set. This will remove all duplicates and create an unordered collection of unique elements.

The result_set now contains the unique elements from the original list of lists:

{1, 2, 3, 4, 5, 6, 7, 8, 9}

Full code

Output

{1, 2, 3, 4, 5, 6, 7, 8, 9}

Conclusion

In this tutorial, we have successfully converted a list of lists to a set in Python using the itertools.chain() function and the built-in set() function. Now you can use this method to easily convert any list of lists to a set and perform various set operations as needed!