guthrie
guthrie

Reputation: 4629

python - match on array return value

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!

Upvotes: 2

Views: 1235

Answers (4)

guthrie
guthrie

Reputation: 4629

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!

Upvotes: 0

Jarret Hardie
Jarret Hardie

Reputation: 98072

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:])

Upvotes: 3

Smashery
Smashery

Reputation: 59733

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

Upvotes: 2

Ayman Hourieh
Ayman Hourieh

Reputation: 137436

You can do it in Python 3 like this:

(a, b, *rest) = seq

See the extended iterable unpacking PEP for more details.

Upvotes: 6

Related Questions