python list pattern matching?

Terry Reedy tjreedy at udel.edu
Fri May 29 00:57:42 CEST 2009


guthrie wrote:
> I want to do a functional like pattern match to get teh 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 find use some notation to do this?
>     [a,b,more] = perms(x)
> or conceptually:
>     [a,b,more..] = perms(x)

 >>> a,b,*rest = list(range(10))
 >>> a,b,rest
(0, 1, [2, 3, 4, 5, 6, 7, 8, 9])
 >>> a,*rest,b = 'abcdefgh'
 >>> a,rest,b
('a', ['b', 'c', 'd', 'e', 'f', 'g'], 'h')




More information about the Python-list mailing list