Search code examples
pythonpython-2.7metasyntactic-variable

Use _ to escape more than one value in a for loop


Say I have the following data structure:

input = [(1,2,3,4,5), (1,2,3,4), (1,2,3)]

In a for loop, I want to iterate over only the first three elements in each tuple element at a time without worrying about how big the tuple is.

I know I can use _ to achieve this, but with it I have to specify how many values I intend to drop.

Is there a way to achieve this without knowing in advance how big the tuple in question is?

I know I can do:

for i, j, k, _, _ in input:
    ....

But is there a way to get away with only one _? As the above will fail if the size of each subelement is not 5 (I will either get need more than 4 values to unpack if too small or too many values to unpack if too big).

I'm asking this out of curiosity, I know I can separately unpack the elements by doing:

for elem in input:     
    i, j, k = elem[:3]

I'm using Python 2.7.6.


Solution

  • You could do for i, j, k, *_ in input: in Python 3.x.