Anthony Lee Meier
Anthony Lee Meier

Reputation: 199

How to unpack a tuple from left to right?

Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?

For example for

j = 1,2,3,4,5,6,7

(1,2,3,4,5,6,7)

v,b,n = j[4:7] 

Can I modify the slice notation so that v = j[6], b=j[5], n=j[4] ?

I realise I can just order the left side to get the desired element but there might be instances where I would just want to unpack the tuple from left to right I think.

Upvotes: 18

Views: 4188

Answers (5)

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

you can try this,

-1 mean looking from reverse, with last 3rd element to last element

>>> v,b,n=j[-1:-4:-1]
>>> print 'v=',v,'b=',b,'n=',n
v= 7 b= 6 n= 5
>>> 

Upvotes: 0

Aguy
Aguy

Reputation: 8059

In case you want to keep the original indices (i.e. don't want to bother with changing 4 and 7 to 6 and 3) you can also use:

v, b, n = (j[4:7][::-1])

Upvotes: 14

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You could ignore the first after reversing and use extended iterable unpacking:

j = 1, 2, 3, 4, 5, 6, 7


_, v, b, n, *_ = reversed(j)

print(v, b, n)

Which would give you:

6 5 4

Or if you want to get arbitrary elements you could use operator.itemgetter:

j = 1, 2, 3, 4, 5, 6, 7

from operator import itemgetter


def unpack(it, *args):
    return itemgetter(*args)(it)

v,b,n = unpack(j, -2,-3,-4)

print(v, b, n)

The advantage of itemgetter is it will work on any iterable and the elements don't have to be consecutive.

Upvotes: 9

joel goldstick
joel goldstick

Reputation: 4493

 n,b,v=j[4:7]

will also work. You can just change the order or the returned unpacked values

Upvotes: 10

Moses Koledoye
Moses Koledoye

Reputation: 78556

This should do:

v,b,n = j[6:3:-1]

A step value of -1 starting at 6

Upvotes: 51

Related Questions