[BangPypers] Python List Comprehension Question

Abhishek L abhishekl.2006 at gmail.com
Thu Oct 2 15:04:44 CEST 2014


On Thu, Oct 2, 2014 at 5:15 PM, kracekumar ramaraju
<kracethekingmaker at 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

should handle that

--
Abhishek


More information about the BangPypers mailing list