Append values to a set in Python
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.
your_set.update(your_sequence_of_values)
e.g, your_set.update([1, 2, 3, 4])
. Or, if you have to produce the values in a loop for some other reason,
for value in ...:
your_set.add(value)
But, of course, doing it in bulk with a single .update
call is faster and handier, when otherwise feasible.