multiple assignment

Christoph Zwerschke cito at online.de
Wed Mar 22 10:45:45 CET 2006


Anand schrieb:
> Suppose i have a big list and i want to take tke the first one and rest
> of the list like car/cdr in lisp.
> is there any easy way to do this in python?
> 
> Only way i know is
> 
> a = range(10)
> x, y = a[0], a[1:]

You have so many higher-level ways to access and iterate through lists 
in Python, that you normally just don't need to do things like that.

Also, in the frequent case where y=a, you can just write x = a.pop(0).

 > Why can't python support something like this:
 >
 > x, *y = a
 >
 > This is not really a new concept to python, infact when calling a
 > function which takes variable  arguments, it is used in a similar way.

You're right, that would not be so far off.
But then, the following should be also supported:

*x, y = a # x, y = a[:-1], y = a[-1]
x, *y, z = a # x, y, z = a[0], a[1:-1], a[-1]

Of course, there can be only one variable with an asterisk.
(But note that in the situation of a function taking parameters, that 
variable must always be the last.)

But I don't know if this is really useful enough...

-- Christoph



More information about the Python-list mailing list