
> list(deepflatten(L, types=list)) # only flatten "inner" lists You could use deepflatten from the 3rd party package iteration_utilities: > from iteration_utilities import deepflatten Example are shown below of the new behavior.
#DUPLICATE CLEANER PRO 3.2.5 KEY CODE#
However, the new code will raise a TypeError when a non-iterable object is given to it.
#DUPLICATE CLEANER PRO 3.2.5 KEY GENERATOR#
Testing the generator works fine with the list that was provided. It fails as one would expect when an inappropriate argument is given to it. The following generator is almost the same as the first but does not have the problem of trying to flatten a non-iterable object. It is confusing and gives the wrong impression of the argument. The problem is that you should not be able to flatten something that is not an iterable. I disagree with the previous implementation. Also, the code relies on the fact that requesting an iterator from a non-iterable raises a TypeError. It will flatten datatypes that you might want left alone (like bytearray, bytes, and str objects). The following generator works fairly well with some caveats: def flatten(iterable): It was fun trying to create a function that could flatten irregular list in Python, but of course that is what Python is for (to make programming fun). Print(list(IT.islice(flatten(infinitely_nested()), 10))) Yield IT.chain(infinitely_nested(), IT.repeat(1)) # 'y', 'Y', 'z', 'Z', 0, 1, 2, 3, 4, 5, 6, 7, 8]Īlthough flatten can handle infinite generators, it can not handle infinite nesting: def infinitely_nested(): Print(list(IT.islice(flatten(IT.chain(IT.repeat(2,3), Here are some examples demonstrating its use: print(list(IT.islice(flatten(IT.repeat(1)),10))) If isinstance(first, ltypes) and not isinstance(first, (str, bytes)): import itertools as ITĭef flatten(iterable, ltypes=collections.Iterable): It is a generator which can handle strings and arbitrary iterables (even infinite ones).

This version of flatten avoids python's recursion limit (and thus works with arbitrarily deep, nested iterables).
