Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to unpack a tuple in Python without creating unwanted variables?

Is there a way to write the following function so that my IDE doesn't complain that column is an unused variable?

def get_selected_index(self):     (path, column) = self._tree_view.get_cursor()     return path[0] 

In this case I don't care about the second item in the tuple and just want to discard the reference to it when it is unpacked.

like image 539
Nathan Avatar asked Sep 27 '10 09:09

Nathan


People also ask

Can you unpack a tuple in Python?

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.

How does tuple unpacking work in Python?

Unpacking Tuples When we put tuples on both sides of an assignment operator, a tuple unpacking operation takes place. The values on the right are assigned to the variables on the left according to their relative position in each tuple . As you can see in the above example, a will be 1 , b will be 2 , and c will be 3 .

Is it possible to unpack tuple items using for loop?

We can do the tuple unpacking right inside the for loop itself because anything you can put on the left-hand side of the equal sign, you can put in between the for and the in in a for loop.

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

In Python the _ is often used as an ignored placeholder.

(path, _) = self._treeView.get_cursor() 

You could also avoid unpacking as a tuple is indexable.

def get_selected_index(self):     return self._treeView.get_cursor()[0][0] 
like image 165
kennytm Avatar answered Oct 13 '22 02:10

kennytm