We will introduce how to convert a list() into a set().
1. set()
Passing a list object to the set()
constructor will add all elements to the set.
my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)
print(my_set)
Output:
{1, 2, 3, 4, 5}
2. Set Comprehension
You can use Set Comprehension to create a set and add all elements of the list as follows.
my_list = [1, 2, 3, 4, 5]
my_set = {x for x in my_list}
print(my_set)
Output:
{1, 2, 3, 4, 5}
3. Unpacking
Using Unpacking, for example, {*my_list}
takes all elements of the list and adds them to the set initial value. In other words, a Set object is created with all elements of the list added.
my_list = [1, 2, 3, 4, 5]
my_set = {*my_list}
print(my_set)
Output:
{1, 2, 3, 4, 5}
Related Posts
- Convert list to set in Python
- 3 Ways to Remove character from a string in Python
- Append an item to the front of list in Python
- Difference between append, extend and insert in Python
- Python - String strip (), rstrip (), lstrip ()
- Python - String Formatting Best Practices (%, str formatting, f-stirng)
- Import python modules in different directories.
- Dynamic import in Python (Reflection in Python)