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?
Append Multiple Values to a Set With the update() Method in Python. The update() method can be used to append multiple values to a set. The update() method is designed to append data-structures like lists and arrays to the set. So, it only takes one argument.
The set add() method adds a given element to a set if the element is not present in the set. Syntax: set. add(elem) The add() method doesn't add an element to the set if it's already present in it otherwise it will get added to the set.
To add multiple elements at once we use the Set update() method. It takes an iterable(list, tuple, dictionary) as an argument. We can add single or multiply iterable in the set using the Update() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With