Skip to content

Python set extend | Example code

  • by

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 the 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 save 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 or suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading