Best way to extract an item from a set of len 1
Fredrik Lundh
fredrik at pythonware.com
Wed Jan 25 10:05:31 EST 2006
Tim Chase wrote:
> I suppose I was looking for something like
>
> >>> item = s.aslist()[0]
>
> which feels a little more pythonic (IMHO). Is one solution
> preferred for speed over others (as this is happening in a fairly
> deeply nested loop)?
the obvious solution is
item = list(s)[0]
but that seems to be nearly twice as slow as [x for x in s][0]
under 2.4. hmm.
here's a faster variant:
item = iter(s).next()
but at least on my machine, your two-step solution
item = s.pop(); s.add(item)
seems to be even faster.
</F>
More information about the Python-list
mailing list