Alex Martelli wrote:
Rene Pijlman [EMAIL PROTECTED] wrote:
Peter Otten:
s = set([one-and-only])
item, = s
...
The comma may easily be missed, though.
You could write:
(item,) = s
But I'm not sure if this introduces additional overhead.
Naah...:
helen:~ alex$ python
Alex Martelli a écrit :
Fredrik Lundh [EMAIL PROTECTED] wrote:
...
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.
Funny, and true on my laptop too:
helen:~ alex$ python -mtimeit -s's=set([23])'
When you have a set, known to be of length one, is there a best
(most pythonic) way to retrieve that one item?
# given that I've got Python2.3.[45] on hand,
# hack the following two lines to get a set object
import sets
set = sets.Set
s = set(['test'])
len(s)
Tim Chase wrote:
When you have a set, known to be of length one, is there a best
(most pythonic) way to retrieve that one item?
s = set([one-and-only])
item, = s
item
'one-and-only'
This works for any iterable and guarantees that it contains exactly one
item. The comma may easily be
Tim Chase [EMAIL PROTECTED] wrote:
...
To get the item, i had to resort to methods that feel less than
the elegance I've come to expect from python:
item = [x for x in s][0]
A shorter, clearer expression of the same idea:
item = list(s)[0]
or
item = list(s).pop()
or the more
Peter Otten:
s = set([one-and-only])
item, = s
item
'one-and-only'
This works for any iterable and guarantees that it contains exactly one
item.
Nice!
The comma may easily be missed, though.
You could write:
(item,) = s
But I'm not sure if this introduces additional overhead.
--
Peter Otten wrote:
When you have a set, known to be of length one, is there a best
(most pythonic) way to retrieve that one item?
s = set([one-and-only])
item, = s
item
'one-and-only'
This works for any iterable and guarantees that it contains exactly one
item. The comma may easily
Fredrik Lundh [EMAIL PROTECTED] wrote:
...
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.
Funny, and true on my laptop too:
helen:~ alex$ python -mtimeit -s's=set([23])' 'x=list(s)[0]'
10 loops, best
Rene Pijlman [EMAIL PROTECTED] wrote:
Peter Otten:
s = set([one-and-only])
item, = s
...
The comma may easily be missed, though.
You could write:
(item,) = s
But I'm not sure if this introduces additional overhead.
Naah...:
helen:~ alex$ python -mtimeit -s's=set([23])'