You are currently viewing Convert List to Set in Python?

How to convert a list to a set in Python? Lists and sets both are built-in data types of Python and they can store collections of elements. However, there are some key differences between them hence, sometimes you would be required to convert list to set.

Advertisements

A list is an ordered collection of elements so, we can add, remove, modify, and slicing elements in a list by using its position/index order. It allows duplicate elements. Sets are a collection of unique elements, similar to a list or a tuple, but with some key differences. Sets do not allow duplicates, and you can perform various mathematical operations on sets such as union, intersection, and difference easily.

You can convert a list to a set in python using many ways, for example, by using the set(), for loop, set comprehension, and dict.fromkeys() functions. In this article, I will explain how to convert a list to a set in python by using all these methods with examples.

1. Quick Examples of Converting List to Set

If you are in a hurry, below are some quick examples of how to convert a list to a set.


# Quick examples of convert list to set

# Initialize list
lists = [5, 2, 3, 4, 3, 5, 4, 6]

# Example 1: Convert the list to a set 
# Using set()
myset = set(lists)

# Example 2: Convert list to set 
# Using for loop
myset = set()
for item in lists:
    myset.add(item)

# Example 3: Convert list to set 
# Using set comprehension
myset = {item for item in lists}

# Example 4: Convert list to set 
# Using dict.fromkeys() method
myset = set(dict.fromkeys(lists))

2. Difference Between List and Set

List Set
A list data structure in many programming languages, such as Python, does allow duplicate elements.A set data structure in many programming languages, such as Python, does not allow duplicate elements.
A list is an ordered collection of elements, which means that the elements in the list are stored in a specific order and can be accessed using their position or index in the list.A set is an unordered collection of elements, which means that the elements in a set have no specific order and cannot be accessed using their position or index.
The elements in a list are enclosed in square brackets [ ]The elements in curly brackets { } denote a set.
A list data structure to implement various other data structures, including Array List, LinkedList, Vector, and Stack.A set data structure to implement various other data structures, including HashSet and LinkedHashSet.
One of the main advantages of using a list data structure is that it allows you to modify its elements by replacing or updating them.In most programming languages, including Python, elements in a set cannot be altered, modified, or replaced directly.
Difference between list and set

3. Convert List to Set Using Python set() Method

You can convert the list to a set using the set() built-in function, This function takes the list as an argument and converts it to the set. Note that in this conversion process, if List has any duplicate values they will be removed as Set can have only unique values.

For example, let’s take a list that contains integers and strings and pass it into set() function to convert the list into set. The resulting set contains only the unique elements of the list, in random order. the integer 12 only appears once in the set, even though it appears twice in the original list.


# Initialize list
lists = [12, 32 , 6, 12, "sparkby","examples"]
print("List:", lists)

# Convert the list to a set using set()
myset = set(lists)
print("Set:", myset)

Yields below output.

python list set

As you can see, from the above code the list contains a ’12’ integer two times but in our resulting set ’12’ has appeared only one time.

4. Convert List to Set Using For Loop

You can also convert a list to a set using a for loop in Python. In this example, first, create a list and an empty set. Then, iterate the given list using for loop, for every iteration, one item from the list is added to the empty set using the add() method.

Note that using the set() function directly is more concise and is the preferred way to convert a list to a set in Python. The use of a for loop in this context might be less efficient and is less idiomatic.


# Initialize the list & set
lists = [5, 2, 3, 4, 3, 5, 4, 6]
myset = set()
print("List:", lists)

# Convert list to set 
# Using for loop
for item in lists:
    myset.add(item)
print("Set:", myset)

Yields below output.

convert list to set in Python

5. Convert List to Set Using Set Comprehension

You can use set comprehension to convert a list to a set in Python. set comprehension is a concise way to create a set. Let’s use set comprehension over the given list to convert it to a set with unique random values. For instance, {item for item in lists} is a set comprehension that creates a set by iterating over each element in lists. The resulting set, myset, will contain the unique elements from the original list.

Note that the curly braces {} are used to define the set comprehension, and the for loop inside the braces defines the iteration. The resulting set myset will contain only unique elements from the original list.


# Convert list to set 
# Using set comprehension
lists = [5, 2, 3, 4, 3, 5, 4, 6]
myset = {item for item in lists}
print("List:", lists)
print("Set:", myset)

# Output:
# List: [5, 2, 3, 4, 3, 5, 4, 6]
# Set: {2, 3, 4, 5, 6}

6. Using dict.fromkeys() Method

Alternatively, using the dict.fromkeys() method of dictionary to convert a list to a set. However, it can be simplified by removing the intermediate step of converting the dictionary keys back to a list before creating the set.


# Convert list to set 
# Using dict.fromkeys() method
lists = [5, 2, 3, 4, 3, 5, 4, 6]
myset = set(dict.fromkeys(lists))
print(myset)

Yields the same output as above.

Frequently Asked Questions on Convert List to Set in Python

How do I convert a list to a set in Python?

You can convert a list to a set in Python using either the set() function, a set comprehension, or the dict.fromkeys() method.

How can I remove duplicates from a list in Python?

Converting the list to a set is a common and effective way to remove duplicates. You can use set() or set comprehension for this purpose.

What is the difference between using set() and set(my_dict.keys())?

The set() function directly converts a list to a set, removing duplicates. On the other hand, set(my_dict.keys()) involves creating a dictionary with unique keys from the list using dict.fromkeys() and then extracting those keys. The latter approach can be less efficient and is generally not recommended for this specific conversion.

Can I use set() with any iterable, not just lists?

You can use the set() function with any iterable in Python, not just lists. The set() function accepts any iterable object, including tuples, strings, and other iterable types.

Why might I choose set() over dict.fromkeys() for converting a list to a set?

Using set() is more concise, direct, and idiomatic for this specific task. dict.fromkeys() is more commonly used for creating dictionaries, and using it to convert a list to a set might be less intuitive.

Conclusion

In this article, I have explained convertion of list to set can be done by using the set(), for loop, set comprehension, and dict.fromkeys() functions. You can use any of the methods as per your need.

Happy Learning !!