Python idiom for taking a single item from a list
In the code sometimes it happens that I have a list, let's call it stuffand I know for sure that this list contains exactly one element. And I want to get this item and put it in a variable, name it. What is the best way to do this? In the past, I used to do this:
thing = stuff[0]
But I think this is not the best idiom. I came up with the best:
(thing,) = stuff
Why is it better?
Readability . This allows the reader to recognize this material has exactly one element.
Free assert: Python stuff , , stuff , - .
: [0] . , , thing = stuff[0]. - , :
thing = some_dict[my_object.get_foobar_handler()][0]
[0] , , , dict lookup. , . :
(thing,) = some_dict[my_object.get_foobar_handler()]
"" ( ): , . stuff[0] , . !
, . ( ). , / , .