Add values to a Python set
This post will discuss how to add values to a set in Python.
1. Add single element
To add an element to a set, the standard function is add(). The following example demonstrates this usage of add().
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = {1, 2, 3} s.add(4) s.add(5) print(s) # {1, 2, 3, 4, 5} |
2. Add contents of another Iterable
If you need to add other iterable contents, you can use the update() function. The following code demonstrates how to add the contents of a list to a set.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = {1, 2, 3} l = [4, 5] s.update(l) print(s) # {1, 2, 3, 4, 5} |
3. Add another Set
You can also use the | operator (or |= operator) to concatenate two sets. Note this returns a new set, as shown below:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': x = {1, 2, 3} y = {4, 5} s = x | y print(s) # {1, 2, 3, 4, 5} |
You can also use the union() function to merge the contents of two sets and return a new set.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': x = {1, 2, 3} y = [4, 5] s = x.union(y) print(s) # {1, 2, 3, 4, 5} |
That’s all about adding values to a set in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)