Search code examples
pythonlistsetunpack

Create a set from a list using `set` vs. unpacking into curly brackets


In Python, a set can be created from a list using either the set constructor or by unpacking the list into curly brackets. For example:

my_list = [1, 2, 3]
my_set = set(my_list)

or

my_list = [1, 2, 3]
my_set = {*my_list}

Are there any specific reasons or use cases where one approach is preferred over the other? What are the advantages or disadvantages of each method in terms of performance, readability, or any other relevant factors?


Solution

  • There is a subtle difference.

    set(my_list) produces whatever the callable bound to set returns. set is a built-in name for the set type, but it's possible to shadow the name with a global or local variable.

    {*my_list}, on the other hand, always creates a new set instance. It's not possible to change what the brace syntax means without modifying the Python implementation itself (and then, you are no longer implementing Python, but a very Python-like language).

    In CPython, using {*mylist} also avoids a function call, it uses BUILD_SET and SET_UPDATE opcodes rather than calling whatever set is bound to.