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

前端 未结 4 558
北海茫月
北海茫月 2020-12-11 00:27

In PyCharm, when I write:

return set([(sy + ady, sx + adx)])

it says \"Function call can be replaced with set literal\" so it repl

4条回答
  •  盖世英雄少女心
    2020-12-11 00:55

    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.

提交回复
热议问题