78

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?

Joshua Ball
  • 23,260
  • 6
  • 27
  • 29
Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103

4 Answers4

85

I personally would write:

a, _, b = myTuple

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 10
    I'd like to note that in the python interpreter `_` is assigned to the result of the last expression (so if you type `'hi'` and hit enter then `_ is 'hi'`) until you do something like this in which you assign a value to it, then it will never work as it did before. – 2rs2ts Oct 13 '15 at 17:47
  • 5
    @2rs2ts for completeness: `_` will work again as it usually does *when your locally-assigned variable `_` leaves scope*, e.g., when an enclosing function ends. To force this to happen at a specific point in your program, you can use `del _`; this explicitly deletes your locally defined variable, `_`, which unmasks the global value, `_`. – CrepeGoat Apr 06 '18 at 18:19
21

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

o17t H1H' S'k
  • 2,541
  • 5
  • 31
  • 52
  • Correct, but I'd clarify that this only works for Python3. – Ataxias Dec 09 '21 at 07:22
  • 4
    there is only python 3 – o17t H1H' S'k Dec 09 '21 at 13:19
  • 1
    Your above statement is demonstrably false. Whether we like it or not, there exist myriads of legacy codes using Python2, and it would be helpful to know what is backward compatible and what isn't (that's why IDE's offer exactly this information). – Ataxias Dec 10 '21 at 20:03
20

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)
Bogdan
  • 8,017
  • 6
  • 48
  • 64
6

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

a,b = some_tuple[0:2]
Spacen Jasset
  • 938
  • 2
  • 11
  • 21