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.
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.
To reverse a Tuple in Python, call reversed() builtin function and pass the tuple object as argument to it. reversed() returns a reversed object.
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.
This should do:
v,b,n = j[6:3:-1]
A step value of -1
starting at 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With