Search code examples
pythonpython-3.xtuplesiterable-unpacking

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.


Solution

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