35

As mentioned here, you can use the star for unpacking an unknown number of variables (like in functions), but only in python 3:

>>> a, *b = (1, 2, 3)
>>> b
[2, 3]
>>> a, *b = (1,)
>>> b
[]

In python 2.7, the best I can come up with is (not terrible, but annoying):

c = (1, 2, 3)
a, b = c[0], c[1:] if len(c) > 1 else []

Is there a way to import this from __future__ like division, or will I need my own function to do unknown-length unpacking in python 2.7?

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
beardc
  • 20,283
  • 17
  • 76
  • 94

3 Answers3

32

in python 2.X, you can do:

c = (1, 2, 3)
a, b = c[0], c[1:]

as long as c has at least one member it will work because if c only has 1 thing in it c[1:] is [].

You should probably make sure there is at least one thing in c though, or else c[0] will raise an exception.

You could do something like:

try:
    c = tuple(c)
    a, b = c[0], c[1:]
except TypeError, IndexError:
    # c is not iterable, or c is iterable, but it doesn't have any stuff in it.
    # do something else
    pass
martineau
  • 119,623
  • 25
  • 170
  • 301
Andbdrew
  • 11,788
  • 4
  • 33
  • 37
  • 4
    Only if `c` is a sequence. Unpacking works with any iterable, so for a full solution, do `c = tuple(c)` first. This emulates the behaviour exactly, including hanging on infinite iterables. But you do still have to work harder for `a, *b, c = range(10)`; but there's no real way around that. – lvc May 29 '12 at 04:28
  • print ImageFileList iflt = tuple(ImageFileList) for x,y in iflt[0], iflt[1:]: why am I still getting an error? ValueError: too many values to unpack ImageFileList is just a list of filenames – Aymon Fournier Jun 29 '16 at 02:36
2
(a,b) = (None, []) if not len(c) else (c[0], c[1:])

is also an option for handling the case where c is an empty sequence, although it won't distinguish between [None] and [] in terms as assignments to a, b. So use it with care, the try / except is probably best.

I can see no real difference between Python 3 and 2.7 when handling an empty container, but the nice thing about Python 3 here is it works with any iterable.

This works in 2.7 if you know c is a generator.

a,b = c.next(), c

But the full beauty of unpacking seems to require Python 3.

Ben
  • 51,770
  • 36
  • 127
  • 149
Pete Cacioppi
  • 880
  • 7
  • 11
-1

answer to ex13.py

from sys import argv

script=argv

def Fun(arg1, *argv): 
    print "First argument :", script 

    for arg in argv: 
        print"Your variable is:", arg

Fun('scrpit', 'first', 'second', 'third')
Nathan Davis
  • 5,636
  • 27
  • 39
  • 4
    While this code may answer the question, providing additional context regarding _why_ and/or _how_ this code answers the question improves its long-term value. – lcnicolau Mar 29 '19 at 02:36