Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore part of a python tuple

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?

like image 739
Jim Jeffries Avatar asked Mar 02 '12 11:03

Jim Jeffries


People also ask

Can I remove item in tuple Python?

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.

What is tuple slicing in Python?

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.

Is Order important in tuple Python?

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.

How do you separate tuples in Python?

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.


2 Answers

I personally would write:

a, _, b = myTuple 

This is a pretty common idiom, so it's widely understood. I find the syntax crystal clear.

like image 61
NPE Avatar answered Sep 21 '22 16:09

NPE


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) 
like image 42
Bogdan Avatar answered Sep 22 '22 16:09

Bogdan