Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append values to a set in Python

Tags:

python

append

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?

like image 359
Alex Gordon Avatar asked Aug 02 '10 22:08

Alex Gordon


People also ask

Can you append values in a set Python?

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.

How do you add items to a set in Python?

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.

How do you add multiple values to a set in Python?

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.


2 Answers

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.

like image 164
Alex Martelli Avatar answered Sep 30 '22 08:09

Alex Martelli


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.

like image 39
RandallShanePhD Avatar answered Sep 30 '22 07:09

RandallShanePhD