4 ms·
You don't need to do that for a set. sets support `len()`. Also set supports `pop()`, so the code is very similar to the list one: assert s and len(s)==1
by viraptor 16y ago
You don't need to do that for a set. sets support `len()`. Also set supports `pop()`, so the code is very similar to the list one:
assert s and len(s)==1
return s.pop()
Or if you want to stay in the immutable land:
assert s and len(s)==1
return tuple(s)[0]
- mccutchen 16y agoBoth of those still fail for other non-list iterables, like generators.
- robrenaud 16y agoThey also have the side effect of removing an item from the collection.
- lehmannro 16y agoA property which is exposed by the article's solution too: >>> x = (lambda: (yield 1))() # generator with one step >>> y = tuple(x)[0] >>> y 1 >>> list(x) # exhausted [] >>> x = (lambda: (yield 1))() >>> y, = x >>> y 1 >>> list(x) # exhausted, too! [] Because that's just what you inevitably need to do to fetch a value from a generator. There is no peeking action or some such.
- deleted 16y ago[deleted]