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?
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?
Define set
Use add to append single values
Use update to append iterable values
Check your collection
That's it - remember, update if it is iterable (aka list or tuple) or add if not. Happy coding!
Use
update
like this:This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with
.add()
, not.update()
.Say you have a string
foo_str
whose contents are'this is a sentence'
, and you have some setbar_set
equal toset()
.If you do
bar_set.update(foo_str)
, the contents of your set will be{'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}
.If you do
bar_set.add(foo_str)
, the contents of your set will be{'this is a sentence'}
.For me, in Python 3, it's working simply in this way:
I don't know if it may be correct...
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,But, of course, doing it in bulk with a single
.update
call is faster and handier, when otherwise feasible.You can also use the
|
operator to concatenate two sets (union in set theory):Or a shorter form using
|=
:Note: In versions prior to Python 2.7, use
set([...])
instead of{...}
.