How to get an item from a simple set?

Bengt Richter bokr at oz.net
Wed Nov 24 12:33:36 EST 2004


On Wed, 24 Nov 2004 15:40:30 GMT, Steven Bethard <steven.bethard at gmail.com> wrote:

>Pete Forman wrote:
>> I have a set that contains one item.  What is the best way of getting
>> at that item?  Using pop() empties the set.  Here is what I've tried.
>
>This is what tuple unpacking is for:
>
> >>> s = set(['foo'])
> >>> item, = s
> >>> item
>'foo'
> >>> [item] = s
> >>> item
>'foo'
>
>It's up to you whether you like the tuple or list syntax better. =)
>
Thanks. I didn't realize a list format could be used to specify target names
like that. My intial reaction is a bendy feeling in my list expression syntax
recognizer, though. I'm not sure I like that on the left hand side.
It feels too much like __setitem__ on some implied object. The tuple syntax
on the left hand side is only for unpacking (unless you want to imagine invoking
an implied unnamed function, but that's a stretch IMO), so it doesn't trigger
that near-miss syntax recognition feeling.

Regards,
Bengt Richter



More information about the Python-list mailing list