On Thu, Oct 2, 2014 at 6:34 PM, Abhishek L <abhishekl.2...@gmail.com> wrote:
> On Thu, Oct 2, 2014 at 5:15 PM, kracekumar ramaraju > <kracethekingma...@gmail.com> wrote: > > Hi > > > > `yield from ` is introduced in Python 3.3 as part of pep 380. > > > > # python 3.3 > > > > from collections import Iterable > > > > def flatten(items): > > for item in items: > > if isinstance(item, Iterable): > > yield from flatten(item) > > else: > > yield item > > Yield from approach is great if you're using python 3.3+ :) > > > > > list(flatten([[1, 2, [3]], 4])) > > [1, 2, 3, 4] > > > > # python 2.7 > > > > from collections import Iterable > > > > x = [[1, 2, [3]], 4] > > > > def flatten(items): > > for item in items: > > if isinstance(item, Iterable): > > for subitem in flatten(item): > > yield subitem > > else: > > yield item > > ....: > > > > list(flatten(x)) > > [1, 2, 3, 4] > > Also you may need to check whether the item is not a string or bytes > or a string in the list will break this, an > > isinstance(item, Iterable) and not isinstance(item,str) # maybe bytes too > > ah, Yes that is correct. Probably flatten can take ignore_types as an argument. condition can be isinstance(item, Iterable) and not isinstance(item, ignore_types) should handle that > > -- > Abhishek > _______________________________________________ > BangPypers mailing list > BangPypers@python.org > https://mail.python.org/mailman/listinfo/bangpypers > -- *Thanks & Regardskracekumar"Talk is cheap, show me the code" -- Linus Torvaldshttp://kracekumar.com <http://kracekumar.com>* _______________________________________________ BangPypers mailing list BangPypers@python.org https://mail.python.org/mailman/listinfo/bangpypers