Add the contents of an Iterable to a Set in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Add the contents of an Iterable to a Set in Python #

Use the set.update() method to add the contents of an iterable to a set, e.g. my_set.update(my_iterable). The set.update() method can be passed one or more iterables and adds the elements of the iterables to the set object.

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

We used the set.update() method to add the elements of an iterable to a set.

If you don't have an existing set, you can directly pass the iterable to the set() class.

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

The set() class takes an iterable optional argument and returns a new set object with elements taken from the iterable.

The set.update() method can be passed one or more iterables and updates the set, adding the elements from the iterables.
main.py
my_set = set() my_list = ['bobby', 'hadz', 'com'] my_tuple = ('a', 'b', 'c') my_set.update(my_list, my_tuple) print(my_set) # 👉️ {'c', 'bobby', 'b', 'a', 'hadz', 'com'}

You can use the update() method with any type of iterable, e.g. a range object.

main.py
my_set = set() my_range = range(5) my_set.update(my_range) print(my_set) # 👉️ {0, 1, 2, 3, 4}

A much more manual approach would be to use a for loop and the set.add() method.

To add the contents of an iterable to a set:

  1. Use a for loop to iterate over the iterable.
  2. Use the set.add() method to add each element to the set.
main.py
my_set = set() my_list = ['bobby', 'hadz', 'com'] for item in my_list: my_set.add(item) print(my_set) # 👉️ {'com', 'bobby', 'hadz'}

We used a for loop to iterate over the list and used the set.add() method to add each list item to the set.

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

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

Using the set.update() method is more performant and should be your preferred approach unless you have to update the values of the iterable before adding them to the set or filter some of them out.

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.