Append values to a set in Python Append values to a set in Python python python

Append values to a set in Python


keep.update(yoursequenceofvalues)

e.g, keep.update(xrange(11)) for your specific example. Or, if you have to produce the values in a loop for some other reason,

for ...whatever...:  onemorevalue = ...whatever...  keep.add(onemorevalue)

But, of course, doing it in bulk with a single .update call is faster and handier, when otherwise feasible.


Define 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}

If you want to add a tuple or frozen-set itself, use add

a.add((5, 6))>> print(a){1, 2, 3, 4, (5, 6)}

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.


You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}>>> my_set = my_set | {2}>>> my_set{1, 2}

Or a shorter form using |=:

>>> my_set = {1}>>> my_set |= {2}>>> my_set{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.