Skip to content

Add list to set Python | Example code

  • by

Use the set update() method or |= operator to Add list to set Python. Set not contains a duplicate so duplicate items will skip. The set update() takes an iterable object as input and adds all its elements to the set.

For example add a list to set Python

Simple example code.

my_set = set((1, 2, 3))
my_list = list([80, 90, 70])

my_set.update(tuple(my_list))
print(my_set)

Output:

Add list to set Python

Another example using |= operator

my_set = set((1, 2, 3))
my_list = list([80, 90, 70])

my_set |= set(my_list)
print(my_set)

Output: {80, 1, 2, 3, 70, 90}

Add all Elements from Multiple Lists to the Set using update() Function

A set update method can take multiple lists.

# input set
set1 = {1, 2, 3, 4}

# 3 lists of numbers
list1 = [5, 6, 7]
list2 = [8, 9]
list3 = [0, 1, 9, 7]

# Add multiple lists
set1.update(list1, list2, list3)

# updated list
print(set1)

Output: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Do comment if you have any doubts or suggestions on this Python list set topic.

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

Your email address will not be published. Required fields are marked *

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