Iterable Flattener with Depth.

Pradeep Jindal praddyjindal at gmail.com
Thu Nov 1 11:06:23 CET 2007


Hi,

5 minute solution to one of my requirements. I wanted to flatten
iterables upto a specific depth.
To be true, didn't search for it on the internet prior to writing this one.


def flatten_iter(my_iter, depth=None):
        """my_iter can be a iterable except string containing nested
        iterables upto any depth. This function will flat all
        (except string) down to a list containing all the elements in
nested-order.
        To add to it you can specify optional depth (int or long)
argument and the
        function will flatten the iterable upto that depth (nesting).
        """
        if not hasattr(my_iter, '__iter__') or isinstance(my_iter, basestring):
                return [my_iter]
        elif depth != None and depth <= 0:
                return my_iter
        temp = []
        for x in my_iter:
                temp.extend(flatten_iter(x, None if depth == None else depth-1))
        return temp

py> temp = [1,[2,[3,4,5],'bash'],6,[7,[8,[9,10,['hi', 'hello']]]], 11, 12]

py> flatten_iter(temp,1)

[1, 2, [3, 4, 5], 'bash', 6, 7, [8, [9, 10, ['hi', 'hello']]], 11, 12]

py> flatten_iter(temp,2)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, [9, 10, ['hi', 'hello']], 11, 12]

py> flatten_iter(temp)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, 9, 10, 'hi', 'hello', 11, 12]

py> flatten_iter(temp,3)

[1, 2, 3, 4, 5, 'bash', 6, 7, 8, 9, 10, ['hi', 'hello'], 11, 12]



Any comments?

Thanks
- Pradeep



More information about the Python-list mailing list