Interesting Python idiom for removing a single item in a single list of entries

Having stumbled upon this today, I thought it might be useful to discuss.

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] , . !

(http://blog.garlicsim.org/post/1198230058/python-idiom-for-taking-the-single-item-from-a-list)

, . ( ). , / , .

?

+3
3

, (1) , (2) (3) , , .

, :

assert len(stuff) == 1, "stuff should have length 1 but has length %d" % len(stuff)
thing = stuff[0]

, .

+7

:

[thing] = stuff

, , (thing,) . .

+2

One of them is likely to skip the comma on its own, and I would rather index the material about the brackets (and that comma) around the thing.

I assume I'm currently connected to a recording thing = stuff[0]

0
source

Source: https://habr.com/ru/post/1766962/


All Articles