Best way to extract an item from a set of len 1
Peter Otten
__peter__ at web.de
Thu Jan 26 03:11:41 EST 2006
Alex Martelli wrote:
> Rene Pijlman <reply.in.the.newsgroup at my.address.is.invalid> 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])' 'x,=s'
> 1000000 loops, best of 3: 0.689 usec per loop
> helen:~ alex$ python -mtimeit -s's=set([23])' '(x,)=s'
> 1000000 loops, best of 3: 0.652 usec per loop
> helen:~ alex$ python -mtimeit -s's=set([23])' '[x]=s'
> 1000000 loops, best of 3: 0.651 usec per loop
>
> ...much of a muchness.
And that is no coincidence. All three variants are compiled to the same
bytecode:
>>> import dis
>>> def a(): x, = s
...
>>> def b(): (x,) = s
...
>>> def c(): [x] = s
...
>>> dis.dis(a)
1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
>>> dis.dis(b)
1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
>>> dis.dis(c)
1 0 LOAD_GLOBAL 0 (s)
3 UNPACK_SEQUENCE 1
6 STORE_FAST 0 (x)
9 LOAD_CONST 0 (None)
12 RETURN_VALUE
Peter
More information about the Python-list
mailing list