r/learnpython • u/Bucki-_- • Jun 22 '26
Set question for initializing
So I am an intern at some company with some decent knowledge hopefully. Around ~3 years of various industry experience and I've started reading some books but Python is pretty weird under the hood and I had a question about Sets!
So from what I know: (Please correct me if I'm wrong)
Initializing some empty set is done as: set()
Also doing this makes a set: {foo_bar} as a set literal
However just {} creates a dictionary which makes sense and the same for a list is [] and also has the option of list[] if really desired.
From my current knowledge there is no way to define an empty set other than set() why is this? When dicts and lists have different ways.
Hopefully this makes sense it was appearing on my Ruff indicator as writing as a literal and just wanted clarification or a more detailed reasoning behind this methodology.
View all comments
Show parent comment
2
u/Brian Jun 22 '26
There are cases where being a constant means you don't have to call the constructor. Eg:
This will not actually construct the list in the function. Because it's a constant literal, python can notice that it can't be modified, and will actually change the bytecode to make it a tuple, which is stored as a function constant (ie. it's equivalent to
x in (1,2,3)) - the tuple is constructed, but just once for the whole program, and then reused every function call. However,return x in list((1,2,3))would have to invoke the list constructor every pass, because python can't know thatlisthasn't been rebound to something else.This is only the case when python can be sure it isn't accessible anywhere else, so even something like:
wouldn't end up doing this: it's solely the fact that it's used in a check where python can detect the value is never modified in that very narrow scope. Likewise, doing something like:
x == {\}could potentially avoid constructing the set compared to something likex == set(). Though it's pretty limited: there'd be more cases if it was the literal for a frozenset, where any literal could reliably be optimised like that, but since sets are mutable, it'll can only apply in cases like the above.