Aug-06-2018, 10:35 AM
(This post was last modified: Aug-06-2018, 10:35 AM by Gribouillis.)
Using a generic function to dispatch according to the argument's type
>>> import functools >>> @functools.singledispatch ... def flatten(x): ... return [x] ... >>> @flatten.register(list) ... @flatten.register(tuple) ... def _(x): ... return [z for y in x for z in flatten(y)] ... >>> a = [[1, 2, 3], [[4]], [5], [['spam','ham','bacon'] , [['foo','bar','baz']], ('x','y','z')], 6] >>> flatten(a) [1, 2, 3, 4, 5, 'spam', 'ham', 'bacon', 'foo', 'bar', 'baz', 'x', 'y', 'z', 6]