Given set s, which of the segments below looks better?
if len(s) == 1:
v = s.copy().pop()
# important stuff using variable v takes place here
or
if len(s) == 1:
v = s.pop()
s.add(v)
# important stuff using variable v takes place here
or
if len(s) == 1:
for v in s:
# important stuff using variable v takes place here
I guess the last segment is the most efficient, but doesn’t it look silly to use a loop that never actually loops?
Why don’t python sets have an alternative method to pop that doesn’t remove the item?
This may seem like a trivial question, but as I’ve run into this scenario multiple times it has become an itch in need of scratching!
You can assign the only element to
vlike this:It raises a exception if
the_setdoesn’t contain exactly one item.