Python set extend | Example code

Unlike list extend(), there is no extend function in the Python set. However, you can use Union, Intersection, Difference, or Symmetric difference method to extend the set in Python.

Read:

Python set extend example

Simple example code using an operator to extend set.

A = {0, 2, 4, 6}
B = {1, 2, 3, 4}

print("Union :", A | B)

print("Intersection :", A & B)

print("Difference :", A - B)

# elements not present both sets
print("Symmetric difference :", A ^ B)

Output:

Python set extend

How can I extend a set with a tuple?

Answer: Use the union method to extend the set with tuple values.

t1 = (1, 2, 3)
t2 = (3, 4, 5)
t3 = (5, 6, 7)

s = set()

s = s.union(t1)
s = s.union(t2)
s = s.union(t3)

print(s)

Or cleaner method

s = set().union(t1, t2, t3)

Output:

{1, 2, 3, 4, 5, 6, 7}

Source: stackoverflow.com

A quick way to extend a set if we know elements are unique

Answer: Use set update to saves allocating a new set all the time so it should be a little faster than set union in Python.

set1 = {1, 2, 3, 4}
set2 = {0, 10}

set1.update(set2)

print(set1)

Output:

{0, 1, 2, 3, 4, 10}

Do comment if you have any doubts and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.