In PyCharm, when I write:
return set([(sy + ady, sx + adx)])
it says "Function call can be replaced with set literal" so it replaces it with:
return {(sy + ady, sx + adx)}
Why is that? A set()
in Python is not the same as a dictionary {}
?
And if it wants to optimize this, why is this more effective?
It is an alternative syntax for
set()
dict
syntax is different. It consists of key-value pairs. For example:Python sets and dictionaries can both be constructed using curly braces:
my_dict = {'a': 1, 'b': 2}
my_set = {1, 2, 3}
The interpreter (and human readers) can distinguish between them based on their contents. However it isn't possible to distinguish between an empty set and an empty dict, so this case you need to use
set()
for empty sets to disambiguate.A very simple test suggests that the literal construction is faster (python3.5):
This question covers some issues of performance of literal constructions over builtin functions, albeit for lists and dicts. The summary seems to be that literal constructions require less work from the interpreter.
Another example how
set
and{}
are not interchangeable (as jonrsharpe mentioned):set([iterable])
is the constructor to create a set from the optional iterableiterable
. And{}
is to create set / dict object literals. So what is created depends on how you use it.