0

What is the difference in the following code snippets?Because the result after set union is same in last three cases.

>>> s=set("Hacker")
>>> s
{'k', 'a', 'e', 'H', 'r', 'c'}

>>> s.union("Rank")

{'c', 'R', 'k', 'n', 'r', 'a', 'e', 'H'}
>>> s.union({"Rank":1})

{'c', 'Rank', 'k', 'r', 'a', 'e', 'H'}
>>> s.union({"Rank":2})

{'c', 'Rank', 'k', 'r', 'a', 'e', 'H'}
>>> s.union({"Rank":3})

{'c', 'Rank', 'k', 'r', 'a', 'e', 'H'}

2 Answers 2

1

when you pass an object to set.union, it's iterated upon.

A dictionary yield its keys when iterated upon, so the values are ignored. And the sole key is "Rank".

A string yields its characters (as strings of length 1) when iterated upon. Passing a string like "Rank" yields R,a,n, and k as strings of 1 character-long.

If you want a dictionary in input and still get the chars, just use a double comprehension:

s.union(c for x in {"Rank":2} for c in x)
Sign up to request clarification or add additional context in comments.

Comments

0

set.union() takes an iterable as parameter and returns a new set containing the union of elements in the initial set + the iterable.

So if you pass a dictionnary as parameter, it will iterate over the dictionnary, which actually iterates over the keys. So in practice all your s.union({"Rank": x}) will return the same value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.