Search code examples
pythontuplesiterable-unpacking

Ignore part of a python tuple


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?


Solution

  • 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)