This blog post suggests an elegant solution I fell in love with:
(item,) = singlet_list
I find it much more readable, and plus it works with any iterable, even if it is not indexable.
EDIT: Let me dig a little more
This construct is called sequence unpacking or multiple assignment throughout the python documentation, but here I'm using a 1-sized tuple on the left of the assignment.
This has actually a behaviour that is similar to the 2-lines in the initial question: if the list/iterable singlet_list is of length 1, it will assign its only element to item. Otherways, it will fail with an appropriate ValueError (rather than an AssertionError as in the question's 2-liner):
>>> (item,) = [1] >>> item 1 >>> (item,) = [1, 2] ValueError: too many values to unpack >>> (item,) = [] ValueError: need more than 0 values to unpack
As pointed out in the blog post, this has some advantages:
- This will not to fail silently, as required by the original question.
- It is much more readable than the
[0] indexing, and it doesn't pass unobserved even in complex statements. - It works for any iterable object.
- (Of course) it uses only one line, with respect to explicitly using
assert