Add list to set Python | Example code

Use 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.

Example add 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

Set update method can take multiple list.

# 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 and suggestions on this Python list set topic.

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.