0

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.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Nobilis
  • 6,592
  • 1
  • 28
  • 58
  • Not a duplicate, none of the answers address my problem and this concerns Python 2 (which I would have been very happy to clarify). I'm genuinely amazed at the speed this got marked as duplicate before I was given a chance to clarify. – Nobilis Nov 10 '15 at 12:21
  • 2
    *"none of the answers address my problem"* - not true, http://stackoverflow.com/a/33528381/3001761 shows you could use `itemgetter` to do it. *"this concerns Python 2"* - so did the other, and the answers are clear that there isn't an unpacking option prior to 3.x. *"before I was given a chance to clarify"* - that chance hasn't ended yet, you can edit the question whenever you like (and *should*, to clarify precisely how this isn't a duplicate, if you're still not satisfied). – jonrsharpe Nov 10 '15 at 12:23
  • @jonrsharpe `itemgetter` is not what I was after as I can't just initialise it and use it in a loop, but I appreciate the replies with respect to Python 3's unpacking syntax, thought that could have been made available to Python 2 somehow. – Nobilis Nov 10 '15 at 12:32
  • 1
    `for i, j, k in map(itemgetter(0, 1, 2), ...):`? – jonrsharpe Nov 10 '15 at 12:34
  • ah, didn't think of applying `map` there, thanks. – Nobilis Nov 10 '15 at 13:32

1 Answers1

4

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

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
John Coleman
  • 46,420
  • 6
  • 44
  • 103