How to get an item from a simple set?

Steven Bethard steven.bethard at gmail.com
Wed Nov 24 18:50:52 CET 2004


Bengt Richter wrote:
> On Wed, 24 Nov 2004 15:40:30 GMT, Steven Bethard <steven.bethard at gmail.com> wrote:
>>
>>>>>[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.

Yeah, I almost always prefer the tuple (comma) syntax, but occasionally 
I find the list syntax clearer, if, for example, I'm unpacking a nested 
single-item list:

 >>> t
[['abcd'], 1, 2]
 >>> (x,), y, z = t
 >>> x, y, z
('abcd', 1, 2)

The ,), in the tuple-only unpacking makes me uncomfortable for some 
reason.  I feel marginally more comfortable with:

 >>> [x], y, z = t
 >>> x, y, z
('abcd', 1, 2)

Of course, I generally feel uncomfortable if I have a weird unpacking 
thing like this anyway.  It pretty much only comes up for me when I want 
to assign some default values in one branch of a try/except or if/else 
statement, e.g.

try:
      x, y = s
except ValueError:
      [x], y = s, None

Steve



More information about the Python-list mailing list