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

Question:

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.

Asked By: Nathan

||

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]
Answered By: kennytm

If you don’t care about the second item, why not just extract the first one:

def get_selected_index(self):
    path = self._treeView.get_cursor()[0]
    return path[0]
Answered By: Steven

it looks pretty, I don’t know if a good performance.

a = (1, 2, 3, 4, 5)
x, y = a[0:2]
Answered By: east

Yes, it is possible. The accepted answer with _ convention still unpacks, just to a placeholder variable.

You can avoid this via itertools.islice:

from itertools import islice

values = (i for i in range(2))

res = next(islice(values, 1, None))  # 1

This will give the same res as below:

_, res = values

The solution, as demonstrated above, works when values is an iterable that is not an indexable collection such as list or tuple.

Answered By: jpp