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
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)
Comments
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.