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

橙三吉。 提交于 2019-12-03 01:04:32

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]

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]

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.

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

a = (1, 2, 3, 4, 5)
x, y = a[0:2]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!