Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle variable length sublist unpacking in Python2?

How to handle variable length sublist unpacking in Python2?

In Python3, if I have variable sublist length, I could use this idiom:

>>> x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)]
>>> for i, *item in x:
...     print (item)
... 
[2, 3, 4, 5]
[4, 6]
[5, 6, 7, 8, 9]

In Python2, it's an invalid syntax:

>>> x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)]
>>> for i, *item in x:
  File "<stdin>", line 1
    for i, *item in x:
           ^
SyntaxError: invalid syntax

BTW, this question is a little different from Idiomatic way to unpack variable length list of maximum size n, where the solution requires the knowledge of a fixed length.

And this question is specific to resolving the problem in Python2.

like image 222
alvas Avatar asked Jan 24 '17 08:01

alvas


Video Answer


1 Answers

Python 2 does not have the splat syntax (*item). The simplest and the most intuitive way is the long way around:

for row in x:
    i = row[0]
    item = row[1:]
like image 158
Amadan Avatar answered Sep 20 '22 02:09

Amadan