6

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.

miken32
  • 39,644
  • 15
  • 91
  • 133
alvas
  • 105,505
  • 99
  • 405
  • 683
  • Duplicate of [Extended tuple unpacking in Python 2](http://stackoverflow.com/q/5333680/2301450) – vaultah Jan 24 '17 at 12:42

4 Answers4

5

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:]
Amadan
  • 179,482
  • 20
  • 216
  • 275
2

If you're planning on using this construct a lot it may be worthwhile writing a little helper:

def nibble1(nested):
    for vari in nested:
        yield vari[0], vari[1:]

then you could write your loop

for i, item in nibble1(x):
    etc.

But I somehow doubt you'll find that elegant enough...

Paul Panzer
  • 49,838
  • 2
  • 44
  • 91
1

You also can do this:

x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)]

for lista in x:
  print (lista[1:])

Or using list comprehension as well:

x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)]

new_li = [item[1:] for item in x]
omri_saadon
  • 9,513
  • 6
  • 31
  • 58
0

You can try This:-

x = [(1, 2,3,4,5), (2, 4,6), (3, 5,6,7,8,9)]
for item in x:
    print (list(item[1:]))
Rakesh Kumar
  • 4,105
  • 2
  • 14
  • 30