Convert list to set in Python

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}
codechachaCopyright ©2019 codechacha