[Baypiggies] Baypiggies snippets

Chad Netzer chad.netzer at gmail.com
Thu Mar 22 03:12:16 CET 2007


On 3/21/07, Keith Dart ♂ <keith at dartworks.biz> wrote:
> Maybe Baypiggies can have a Python snippets night? or a snippets area
> on the web site.

A good idea, and actually related to another idea I had today.  I was
thinking about a "There's more than one way to do it in Python, too"
type-thing, and I was going to solicit examples from the list.  I
figured it could generate some instructive examples for newbies night.

As an example:

seq = [1,2,3]  # or almost any collection, string, etc

# Here is an expression to check for the nonexistence of an item in a
collection,
# that is idiomatic in many languages
not 1 in seq    # ie. not (1 in seq)

# But in python, you can also say:
1 not in seq


A simple example, but I find the second one more pythonic, and worth
knowing early on.  I'd love to see other simple contributions of
pythonic "There is more than one way to do it". :)


> Here is one I recently did. Any comments? Improvements?
>
> def flatten(alist):

[snipped]

Keith,

   Just FYI, there is a flatten function in Tkinter.py (which was
written pre-2.0, and is showing its age, but it works fine...).  The
modern version is written in C, but the original is still in
Tkinter.py (as a fallback):

def _flatten(tuple):
    """Internal function."""
    res = ()
    for item in tuple:
        if type(item) in (TupleType, ListType):
            res = res + _flatten(item)
        elif item is not None:
            res = res + (item,)
    return res


Note the structural similarity with your code, just done in an "older"
style (ie. TupleType, use of "tuple" variable, etc.)  Note also that
the Tkinter.py version (which isn't used anymore) exhibits quadratic
run time behavior, due to repeated tuple appends.  The "fix" was what
you did; to use list appends.

This flatten function has some nostalgic meaning for me: I had just
discovered Python, and in early 1998 noticed the quadratic behavior,
and posted to the mailing list.  It prompted a reply from Guido, and
even got him to rewrite it in C for version 1.5, with linear behavior.
 Ahhh, the memories. :)

So, just to be clear, the modern tkinter _flatten is NOT quadratic,
but linear and C.  Which means, Keith, if you want a really fast
flatten(), try Tkinter._flatten().

Chad


More information about the Baypiggies mailing list