I'm surprised nobody has mentioned this, but it appears there is actually a difference between those two syntaxes from what I can tell—and that is performance/optimization.
For most situations the difference should be negligible, but in your example the following is creating a set
from items directly:
my_set = {'foo', 'bar', 'baz'}
While the following creates a list
and then passes it to the set
constructor:
my_set = set(['foo', 'bar', 'baz'])
The end results are equivalent, but we're getting them two slightly different ways. As you'd expect, the second one is a bit slower:
❯ python -m timeit 'my_set = {"foo", "bar", "baz"}'
10000000 loops, best of 5: 37.3 nsec per loop
❯ python -m timeit 'my_set = set(["foo", "bar", "baz"])'
5000000 loops, best of 5: 92.3 nsec per loop
As far as I'm aware, the {}
literal syntax is the only way to skip creating an intermediate iterable when constructing a set
. It's a little odd to me personally that the set
constructor wasn't instead designed to take a variable number of positional arguments like so:
# This usage is invalid in real Python. If it existed,
# I would expect the call to be exactly equivalent
# to the performance of the literal syntax.
>>> set("foo", "bar", "baz")
# You would then construct a `set` from an existing
# `list` by simply unpacking the sequence.
>>> set(*["foo", "bar", "baz"])
Unfortunately, that signature doesn't exist.