How to Add List to Set in Python
We have several ways of adding the elements of a list to a set in Python.
Suppose we want to add the elements of curr_list
into curr_set
to create a set of { 1, 2, 3 }
.
curr_set = set(1)
curr_list = [2, 3]
Quick caveat: if we want to add the entire list as a single element to the set, we’ll have to first convert it to a tuple.
curr_set.add(tuple(curr_list)) # { 1, (2, 3) }
To add all the list elements to a set, we have multiple options.
1. Using update()
We can add all elements from a list using update()
.
curr_set.update(curr_list)
2. Using the set union operator (|
)
The update()
method applies the |
operator under the hood.
curr_set |= set(curr_list)
3. Using union()
We can also use union()
to add a list to a set.
curr_set.union(curr_list)