What is the usual/clearest way to write this in Python?
value, _ = func_returning_a_tuple()
or:
value = func_returning_a_tuple()[0]
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.
Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.
When we are unpacking values into variables using tuple unpacking, the number of variables on the left side tuple must exactly match the number of values on the right side tuple . Otherwise, we'll get a ValueError .
Because parentheses of tuples can be omitted, multiple values can be assigned to multiple variables in one line as follows. An error is raised if the number of variables does not match the number of elements.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With