Append values to a set in Python


Question

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?

1
316
12/6/2017 2:01:22 PM

Accepted Answer

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.

356
8/2/2010 10:43:15 PM

Define set

a = set()

Use add to append single values

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

Use update to append iterable values

a.update([3,4])

Check your collection

a
Out[*n*]: {1, 2, 3, 4}

That's it - remember, update if it is iterable (aka list or tuple) or add if not. Happy coding!


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon