MEME
MEME

Reputation: 15

Adding items in set (Python)

I just start learning about adding items in set (Python), but then I don't understand why this happens

thisset = {"apple", "banana", "cherry"}

thisset.update("durian", "mango", "orange")

print(thisset)

and I get the output like this:

{'i', 'o', 'r', 'm', 'cherry', 'n', 'u', 'a', 'apple', 'banana', 'd', 'e', 'g'}

What I want is put the other 3 items into the set, what else I need to add/change?

Upvotes: 1

Views: 75

Answers (2)

dulq
dulq

Reputation: 245

According to the reference, set.update(*others) will update the set, adding elements from all others, what it does is set |= other | .... So in your case, what thisset.update("durian", "mango", "orange") does is thisset |= set("marian") | set("mango") | set("orange"). To accomplish what you want, you need to pass a list or a set, say thisset.update(["durian", "mango", "orange"]) or thisset.update({"durian", "mango", "orange"}).

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

You need to put curly braces inside update:

>>> thisset = {"apple", "banana", "cherry"}
>>> thisset.update({"durian", "mango", "orange"})
>>> thisset
{'orange', 'banana', 'mango', 'apple', 'cherry', 'durian'}
>>> 

Upvotes: 0

Related Questions