What is the usual/clearest way to write this in Python?
value, _ = func_returning_a_tuple()
or:
value = func_returning_a_tuple()[0]
What is the usual/clearest way to write this in Python?
value, _ = func_returning_a_tuple()
or:
value = func_returning_a_tuple()[0]
For extracting a single item, indexing is a bit more idiomatic. When you're extracting two or more items, unpacking becomes more idiomatic. That's just empirical observation on my part; I don't know of any style guides recommending or mandating either choice!-)
value = func_returning_a_tuple()[0]
seems clearer and also can be generalized.
What if the function was returning a tuple with more than 2 values?
What if the program logic is interested in the 4th element of an umpteen tuple?
What if the size of the returned tuple varies?
None of these questions affects the subcript-based idiom, but do in the case of multi-assignement idiom.
If you'd appreciate a handy way to do this in python3.x, check out the python enhancement proposal (PEP) 3132 on this page of What's New in Python:
Extended Iterable Unpacking. You can now write things like a, b, *rest = some_sequence
. And even *rest, a = stuff
. The rest object is always a (possibly empty) list; the right-hand side may be any iterable. Example:
(a, *rest, b) = range(5)
This sets a
to 0
, b
to 4
, and rest
to [1, 2, 3]
.