Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 622
Anthony Lee Meier Avatar asked Jul 08 '16 22:07

Anthony Lee Meier


People also ask

How do you unpack a tuple?

Summary. Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

How do you reverse a tuple order?

To reverse a Tuple in Python, call reversed() builtin function and pass the tuple object as argument to it. reversed() returns a reversed object.

How do you separate a tuple?

To split a tuple, just list the variable names separated by commas on the left-hand side of an equals sign, and then a tuple on the right-hand side.


1 Answers

This should do:

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

A step value of -1 starting at 6

like image 122
Moses Koledoye Avatar answered Oct 09 '22 16:10

Moses Koledoye