Ignore part of a python tuple

PythonTuplesIterable Unpacking

Python Problem Overview


If I have a tuple such as (1,2,3,4) and I want to assign 1 and 3 to variables a and b I could obviously say

myTuple = (1,2,3,4)
a = myTuple[0]
b = myTuple[2]

Or something like

(a,_,b,_) = myTuple

Is there a way I could unpack the values, but ignore one or more of them of them?

Python Solutions


Solution 1 - Python

I personally would write:

a, _, b = myTuple

This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.

Solution 2 - Python

Your solution is fine in my opinion. If you really have a problem with assigning _ then you could define a list of indexes and do:

a = (1, 2, 3, 4, 5)
idxs = [0, 3, 4]
a1, b1, c1 = (a[i] for i in idxs)

Solution 3 - Python

you can use *_ to capture an unknown number of elements e.g.

first, *_, one_before_last, _ = 1,2,3,4,5,6,7,8,9

gives:

first = 1
one_before_last = 8

Solution 4 - Python

Note that you can slice the source tuple, like this instead:

a,b = some_tuple[0:2]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJim JeffriesView Question on Stackoverflow
Solution 1 - PythonNPEView Answer on Stackoverflow
Solution 2 - PythonBogdanView Answer on Stackoverflow
Solution 3 - Pythono17t H1H' S'kView Answer on Stackoverflow
Solution 4 - PythonSpacen JassetView Answer on Stackoverflow