tags:

views:

337

answers:

4

I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value.

For example, assume that perms(x) returns a list of values, and I want to do this:

seq=perms(x)
a = seq[0]
b = seq[1]
rest = seq[2:]

Of course I can shorten to:

[a,b] = seq[0:2]
rest  = seq[2:]

Can I use some notation to do this?

[a,b,more] = perms(x)

or conceptually:

[a,b,more..] = perms(x)

PROLOG & functional languages do list decomposition so nicely like this!

+6  A: 

You can do it in Python 3 like this:

(a, b, *rest) = seq

See the extended iterable unpacking PEP for more details.

Ayman Hourieh
+2  A: 

For Python 2, I know you can do it with a function:

>>> def getValues(a, b, *more):
    return a, b, more

>>> seq = [1,2,3,4,5]
>>> a, b, more = getValues(*seq)
>>> a
1
>>> b
2
>>> more
(3, 4, 5)

But not sure if there's any way of doing it like Ayman's Python 3 suggestion

Smashery
a little shorter: a,b,m = (lambda a,b,*more:(a,b,more))(*seq)
Javier
this is the way for python-2.x
van
+3  A: 

In python 2, your question is very close to an answer already:

a, b, more = (seq[0], seq[1], seq[2:])

or:

(a, b), more = (seq[0:2], seq[2:])
Jarret Hardie
A: 

Very nice, thanks.

The suggestions where one dissects the array on the fight-hand side don't work so well for me, as I actually wanted to pattern match on the returns from a generator expression.

for (a, b, more) in perms(seq): ...

I like the P3 solution, but have to wait for Komodo to support it!

Guthrie