Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple unpacking: dummy variable vs index

What is the usual/clearest way to write this in Python?

value, _ = func_returning_a_tuple()

or:

value = func_returning_a_tuple()[0]
like image 347
Peter Graham Avatar asked Apr 06 '10 05:04

Peter Graham


People also ask

Is unpacking possible in a tuple?

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.

What is unpacking of 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.

How does tuple unpacking work in Python?

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 .

When unpacking a tuple What happens if the number of variables on the left doesn't match the number of items in the tuple?

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.


1 Answers

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].

like image 53
physicsmichael Avatar answered Sep 19 '22 15:09

physicsmichael