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

Nathan picture Nathan · Sep 27, 2010 · Viewed 17.1k times · Source

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.

Answer

kennytm picture kennytm · Sep 27, 2010

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]