Append values to a set in Python

I have a set like this:

keep = set(generic_drugs_mapping[drug] for drug in drug_input)

How do I add values [0,1,2,3,4,5,6,7,8,9,10] into this set?

8 s
8

Define a set

a = set()

Use add to append single values

a.add(1)
a.add(2)

Use update to add elements from tuples, sets, lists or frozen-sets

a.update([3, 4])
>>> print(a)
{1, 2, 3, 4}

Note: Since set elements must be hashable, and lists are considered mutable, you cannot add a list to a set. You also cannot add other sets to a set. You can however, add the elements from lists and sets as demonstrated with the .update method.

Leave a Comment