parsed.org

Tips by tag: lists

Flatten Lists by http://hawk.mckain.myopenid.com/ on Sep 02, 2007 04:17 AM

Flattens a list of any depth:

def flatten(seq, a = []):
    """flatten(seq, a = []) -> list

    Return a flat version of the iterator `seq` appended to `a`
    """

    if hasattr(seq, "__iter__"):  # Can `seq` be iterated over?
        for item in seq:          # If so then iterate over `seq`
            flatten(item, a)      # and make the same check on each item.
    else:                         # If seq isn't an iterator then
        a.append(seq)             # append it to the new list.
    return a
dataflattenlistspython
RSS