Why is it possible to replace sometimes set() with {}?

PythonSet

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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):

>>> timeit.timeit('a = set([1, 2, 3])')
0.5449375328607857
>>> timeit.timeit('a = {1, 2, 3}')
0.20525191631168127

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.

Solution 2 - Python

It is an alternative syntax for set()

>>> a = {1, 2}
>>> b = set()
>>> b.add(1)
>>> b.add(2)
>>> b
set([1, 2])
>>> a
set([1, 2])
>>> a == b
True
>>> type(a) == type(b)
True

dict syntax is different. It consists of key-value pairs. For example:

my_obj = {1:None, 2:None}

Solution 3 - Python

set([iterable]) is the constructor to create a set from the optional iterable iterable. And {} is to create set / dict object literals. So what is created depends on how you use it.

In [414]: x = {}

In [415]: type(x)
Out[415]: dict

In [416]: x = {1}

In [417]: type(x)
Out[417]: set

In [418]: x = {1: "hello"}

In [419]: type(x)
Out[419]: dict

Solution 4 - Python

Another example how set and {} are not interchangeable (as jonrsharpe mentioned):

In: f = 'FH'

In: set(f)
Out: {'F', 'H'}

In: {f}
Out: {'FH'}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlivier PonsView Question on Stackoverflow
Solution 1 - PythonsnakecharmerbView Answer on Stackoverflow
Solution 2 - PythonDhruvPathakView Answer on Stackoverflow
Solution 3 - PythonC PandaView Answer on Stackoverflow
Solution 4 - PythonEmanuelView Answer on Stackoverflow