I created this function sometime ago for my own purposes. It simply flattens a list.
Check out the first comment for another version of someone else's design.
Python, 8 lines
1 2 3 4 5 6 7 8
# flattens a list eg. flatten(1, 2, ['b','a','c']) = [1, 2, 'a', 'b', 'c'] def flatten(*args): for x in args: if hasattr(x, '__iter__'): for y in flatten(*x): yield y else: yield x
How about this?
I am not that familiar with the yield statement. Could you please explain further?
Sherry that's brilliant with way less code and all the goodies from generators ;) way better than other's version ...
Sunjay Varma as you can see there are always more efficient ways to code things , especially in interpreted languages , so it is not polite to criticize other people codes in that manner ... in my opinion this site supposed to be about learning and sharing not judging ...
Sorry about that. I didn't mean to seem rude. I only posted because I thought that the community would benefit from different versions of functions.
Thanks to this recipe, we now have a great generator version as well.
Just something to add, Sherry's recipe above is very good for iteration, but for list stuff, you would have to add the extra statement
Which might be inconvenient for some people.
Sorry back so late, I do not always online.
Sunjay Varma, as you see, generator is a simpler, faster and more memory efficient way(I like it ^ ^). For more information, you can read the python official documentation: http://docs.python.org/reference/simple_stmts.html#the-yield-statement.
Except generators, I used "hasattr(x, '__iter__')" instead of "isinstance(x, (list, tuple))" to check the argument can be iterative. Not only list and tuple, I hoped it also work for set, xrange(python 2.x), generator and iterator types. For example:
More information: http://docs.python.org/library/stdtypes.html#built-in-types.
Lastly, I prefer to use generators if there is not necessary to get all elements and creat a list to memorize them. Maybe using a for loop is better?
Sorry for my poor English. Enjoy.
Thanks I agree completely. :)