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?
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement.
Tuple slicing is basically used to obtain a range of items. Furthermore, we perform tuple slicing using the slicing operator. We can represent the slicing operator in the syntax [start:stop:step]. Moreover, it is not necessary to mention the 'step' part.
While they don't maintain order, in some python versions they'll return a consistent order, while other versions deliberately randomize the order to make sure you don't depend on it.
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.
I personally would write:
a, _, b = myTuple
This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.
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)
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