Question

I often run into the situation where I am querying some data source that returns a list, however I'm expecting the list to contain only a single element. Right now I do:

el = result_list[0]

maybe in a try block in case the list is empty. But, I don't like it. What is the best way? It would be cool to do this:

el = result_list.only()

And perhaps that could puke if the list is empty or has more than one element.

Was it helpful?

Solution

In Python 2 or 3:

>>> a, = [1]
>>> a
1

>>> a, = []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack

>>> a, = [1,2,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)

In Python 3, you can also

>>> a,*_ = [1,2,3]
>>> a
1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top