[BangPypers] Python List Comprehension Question

kracekumar ramaraju kracethekingmaker at gmail.com
Thu Oct 2 13:45:41 CEST 2014


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

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]

PEP 0380: http://legacy.python.org/dev/peps/pep-0380/

P.S: The above approach is discussed in Python 3 CookBook by David Beazley.



On Thu, Oct 2, 2014 at 4:27 PM, Anand Chitipothu <anandology at gmail.com>
wrote:

> On Thu, Oct 2, 2014 at 3:51 PM, Rajiv Subramanian M <rajiv.m1991 at gmail.com
> >
> wrote:
>
> > Hello Group,
> >
> > I'm Rajiv working as web developer in bangalore.
> >
> > Objective:
> > We need to convert the list containing integers and nested list of
> integer
> > in it
> > e.g.) x = [[1, 2, [3]], 4]
> > into a flat list format
> > e.g.) result = [1, 2, 3, 4]
> >
> > MyAnswer using Recursive function:
> > def flat_it(List):
> >     result = []
> >     for item in List:
> >         if type(item) is int:
> >             result.append(item)
> >         else:
> >             result += flat_it(item)
> >     return result
> > print flat_it(x)
> >
> > This actually works, but I tried to optimize this with List comprehension
> > like the following code, but it never worked
> >
> > def flat_it(List):
> > return [item if type(item) is int else flat_it(item) for item in List]
> > print flat_it(x)
> >
> > This returns result without flatting like what i passed in argument [[1,
> 2,
> > [3]], 4]
> >
>
> List comprehensions take a list and return a list of the same size (if you
> don't use if condition).
>
> What you have done is correct solution, though it could be slightly
> improved like the following:
>
> def flat_it(values, result=None):
>     if result is None:
>         result = []
>
>     for v in values:
>         if isinstance(v, list):
>             flat_it(v, result)
>         else:
>             result.append(v)
>     return result
>
> Improvements:
> * using isinstance is better than comparing type.
> * avoids creation of intermediate lists by passing the result along the
> recursive calls
>
> Anand
> _______________________________________________
> BangPypers mailing list
> BangPypers at 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>*


More information about the BangPypers mailing list