Extend a Set object in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Extend a Set object in Python #

Use the set.update() method to extend a set object, e.g. my_set.update(['bobby', 'hadz']). The update() method takes an iterable and extends the set by adding all elements from the iterable to it.

main.py
my_set = set() my_set.update(['bobby', 'hadz']) print(my_set) # 👉️ {'hadz', 'bobby'}

We used the set.update method to extend a set.

Set objects are an unordered collection of unique elements, so the insertion order is not preserved.

The method takes an iterable, e.g. a list, tuple or another set and adds all of the elements of the iterable to the set.

main.py
my_set = set() my_set.update({'bobby', 'hadz', '.com'}) print(my_set) # 👉️ {'.com', 'hadz', 'bobby'}

Alternatively, you can use a for loop to iterate over the iterable and use the set.add() method to extend the set.

main.py
my_set = set() my_list = ['bobby', 'hadz', 'com'] for item in my_list: my_set.add(item) print(my_set) # 👉️ {'hadz', 'bobby', 'com'}

The set.add method adds the provided element to the set.

main.py
my_set = set() my_set.add('a') my_set.add('b') my_set.add('a') print(my_set) # 👉️ {'a', 'b'}

You can also use the set.union method to extend a set.

main.py
my_set = set() my_list = ['bobby', 'hadz', 'com'] result = my_set.union(my_list) print(result) # 👉️ {'hadz', 'com', 'bobby'}

The set.union method returns a new set with elements from the set and the provided iterables.

A common mistake when using set.update() is to forget to pass a list or a tuple containing the values you want to add to the set and instead pass the values directly.

main.py
my_set = set() my_set.update('bobby', 'hadz') print(my_set) # 👉️ {'z', 'h', 'a', 'o', 'y', 'd', 'b'}

The update() method takes an iterable and strings are iterable, so it just split the strings into characters and added the characters to the set.

Instead, we should have passed a tuple or a list containing the values to the set.update() method.

main.py
my_set = set() my_set.update(['bobby', 'hadz']) print(my_set) # 👉️ {'hadz', 'bobby'}
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.