pattern matching in python

Tim Peters tim.one at home.com
Fri Jan 12 03:19:16 EST 2001


[Quinn Dunkan]
> Every once in a while, I remember that python does basic tuple
> pattern-matching, which doesn't seem to come up much in the
> documentation, except for things like 'a, b = f()'.  Specifically,
> nested matching, like:
>
> t = [ (1, (2, 3), 4), ]
> for (a, (x, y), b) in t: ...
>
> I recently noticed, that, of course,
>
> def f(a, (x, y), b): ...
>
> works too.  Is this standard, documented behaviour that can be
> relied on?

Yup.  Guido has mentioned that he might drop the arglist gimmick in P3K,
though, as it's conspicuous by absence in real Python programs.  Or maybe I
made that up!  It's hard to tell.

> ok-so-where's-the-cons-operator-ly y'rs

def car(x):
    return x[0]

def cdr(x):
    return x[1]

def cons(x, y):
    return x, y

has the same semantics (cdr(cons(x,y)) is y; etc), and similar pragmatics
(O(1) cons, car cdr; O(N) search; etc).  Say None instead of NIL.  Then
throw it all out and use a language where it's natural instead <wink>.
Curiously, the profiling module actually uses this way of building a stack,
because at the time Jim Roskind found it was quicker than pushing and
popping a list.

most-code-is-left-over-from-decade-old-statistics<wink>-ly y'rs  - tim





More information about the Python-list mailing list