Pythonic way to take the only item from a list

时间:2015-07-28 16:20:37

标签: python

Sometimes a function returns a list, but you know it has only one item. One way to get it is

a = somefunc()[0]

If the list has more than one item, they will be silently discarded.

This article suggests using

(a,) = somefunc()

A comment proposes just

a, = somefunc()

Both have the advantage that an array with more than one element gives a ValueError: too many values to unpack. They also work with tuples, sets, and other collections.

Are those methods considered Pythonic or confusing? Do they have any drawbacks?

2 个答案:

答案 0 :(得分:5)

I've always taken preference in

(a,) = somefunc()

for exactly the reasons pointed out in the article. It assumes only 1 element in the list. It is easier to read. And it makes the assertion for you.

答案 1 :(得分:5)

If you are using Python3 a good method is to unpack the remaining values into a variable that can be accessed or not. This avoids raising a ValueError in the chance that more than one value is returned.

>>> a, *b = ['this', 'that', 'other']
>>> a
'this'
>>> b
['that', 'other']