bad recursion, still works

iu2 israelu at elbit.co.il
Tue Jul 15 14:59:08 EDT 2008


Hi,

I wrote this wrong recursive function that flattens a list:

def flatten(lst, acc=[]):
    #print 'acc =', acc, 'lst =', lst
    if type(lst) != list:
        acc.append(lst)
    else:
        for item in lst:
            flatten(item)
    return acc

a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14]
b = flatten(a)
print b

I was amazed to realize that it flattens the list alright. Why? 'acc'
should be an empty list on each invocation of flatten, but is seems to
accumulate anyway...




More information about the Python-list mailing list