What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Convert List to Set in Python | 4 Methods (With Example)

  • Sep 15, 2023
  • 5 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kaustubh Saini
Convert List to Set in Python | 4 Methods (With Example)

In Python, data structures play a crucial role in managing and organizing data effectively. Two commonly used data structures are lists and sets. Lists allow you to store multiple elements in a single variable, while sets ensure that each element is unique. Converting a list to a set can be useful in scenarios where you need to remove duplicates or perform set operations on the data. In this article, we will explore various methods to convert a list to a set in Python.

What is a List? 

A list is an ordered collection of elements enclosed in square brackets ([]). It allows duplicate elements and preserves the order of insertion. Lists are mutable, meaning you can modify their elements after they are created. Here's an example of a list:

my_list = [1, 2, 2, 3, 3, 4, 5]


What is a Set? 

A set is an unordered collection of unique elements enclosed in curly braces ({}). It does not allow duplicate elements and does not preserve the order of insertion. Sets are useful when you need to perform membership checks or remove duplicates from a collection. Here's an example of a set:

my_set = {1, 2, 3, 4, 5}


Difference Between List and Set in Python

Feature List  Set
Ordering Ordered Unordered
Duplicates Allows duplicates Doesn't allow duplicates
Syntax Defined using square brackets [] Defined using curly braces {} or set() function
Access Method Index based Can't be accessed by an index; elements can be checked for membership
Mutability Mutable (can change its content) Mutable (but its elements must be immutable, like strings, numbers)
Data Types Can store mixed data types Can store mixed data types, but only immutable ones
Methods Has methods like append(), remove(), extend() etc. Has methods like add(), remove(), union(), intersection() etc.
Use Case When order and indexing is required When you need to ensure unique values and perform set operations

 

How to Convert a List to Set in Python?

In Python, we have four different ways to transform a list into a set. Let's take a closer look at each method step by step.

Method 1: Using the set() Function

The simplest and most straightforward method to convert a list to a set in Python is by using the set() function. The set() function takes an iterable, such as a list, as an argument and returns a set containing all the unique elements from the iterable. Here's an example:

my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set(my_list)
print(my_set)


Output:

{1, 2, 3, 4, 5}


In this example, the set() function is applied to the list my_list, resulting in a set my_set that contains only the unique elements of the list.

Method 2: Using a For Loop and the add() Method 

Another method to convert a list to a set is by using a for loop to iterate over each element of the list and adding it to a set using the add() method. Here's an example:

my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set()

for element in my_list:
    my_set.add(element)

print(my_set)

 

Output:

{1, 2, 3, 4, 5}


In this example, we create an empty set my_set and then iterate over each element of the list my_list. We add each element to the set using the add() method, which automatically handles duplicates and ensures that only unique elements are added to the set.

Method 3: Using Set Comprehension

Set comprehension is a concise and elegant way to generate sets in Python. It allows you to create a set in a single line of code, using an in-place for loop to iterate over the elements of a list. Here's an example:

my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = {x for x in my_list}

print(my_set)


Output:

{1, 2, 3, 4, 5}

 

In this example, we use a set comprehension to convert the list my_list into a set my_set. The set comprehension iterates over each element x in the list and adds it to the set, resulting in a set that contains only the unique elements of the list.

Method 4: Using the dict.fromkeys()

Though not as commonly used as the previous methods, you can also convert a list to a set by first converting the list to a dictionary using the dict.fromkeys() method, and then extracting the keys of the dictionary as a set. Here's an example:

my_list = [1, 2, 3, 3, 4, 5, 5]
my_dict = dict.fromkeys(my_list)
my_set = set(my_dict)

print(my_set)

 

Output:

{1, 2, 3, 4, 5}

 

In this example, we first use the dict.fromkeys() method to create a dictionary my_dict from the list my_list. The values of the dictionary are set to None, but what matters to us are the keys, which are the unique elements of the list. Finally, we convert the keys of the dictionary to a set my_set, resulting in a set that contains only the unique elements of the list.

Conclusion

In this article, we explored different methods to convert lists to sets in Python. We learned that lists are ordered collections that allow duplicates, while sets are unordered collections that only contain unique elements.

By using the set() function, a for loop with the add() method, set comprehension, or the dict.fromkeys() method, you can easily convert a list to a set and remove any duplicate elements.

Similarly, you can refer to our article on converting a set to list in Python. Remember to choose the method that best suits your needs and consider the time complexity for efficiency.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kaustubh Saini
I'm Kaustubh Saini, founder of FavTutor. I have a genuine passion for coding and data science. In my articles, I aim to break down complex topics, share coding insights, and make learning more accessible. When I'm not writing, I'm always exploring ways to enhance your learning experience at FavTutor.