Python idiom for taking the single item from a list
blog.garlicsim.org
Python idiom for taking the single item from a list
1–10 of 97 posts
Re: Python idiom for taking the single item from a list
#2Re: Python idiom for taking the single item from a list
#3Re: Python idiom for taking the single item from a list
#4Very good idea, I support this and will use it from now on (even though I don't like the (thing,) Python syntax very much), as it's the only way to say that the iterable should only have one element.
[thing] = stuff
works too. I think I like that even better.
Re: Python idiom for taking the single item from a list
#5Re: Python idiom for taking the single item from a list
#6so if I was wrong in my original assumption that stuff has exactly one element, Python will shout at me before this will manifest itself as a hard-to-find bug someplace else in the program.
and then later on,
This method works even when stuff is a set or any other kind of collection. stuff[0] wouldn’t work on a set because set doesn’t support access by index number.
The second argument is basically in favor of duck-typing which is the pythonic way of writing code, ie, not caring about the actual object but only if it responds to the given message.
But what about the first argument? Couldn't you make the case that the pythonic way of handling it is to only care about if the object responds to __getitem__(0)?
Which idiom you use would depend entirely on context, wouldn't it?
Re: Python idiom for taking the single item from a list
#7thing, = stuff works too.
Re: Python idiom for taking the single item from a list
#8 if 1==len(lst):
return lst[0]
else:
return reduce(fn, lst)
I don't really want to have to do: if 1==len(lst):
(single,)=lst
return single
else:
return reduce(fn, lst)Re: Python idiom for taking the single item from a list
#9I've never found a case where I knew there would only be one element in a list, but I do use tuple unpacking all of the time.
Pretty cool I guess; didn't know it wasn't a common idiom. Good to know. Thanks for sharing. :)