[BangPypers] Python List Comprehension Question

Bhargav Kowshik bhargav.kowshik at yahoo.com
Fri Oct 3 16:56:33 CEST 2014


We could use what Anand talked about at Pycon India about handling the headers in first row of a CSV.In this scenario, instead of default for result being None and checking if None everytime, we could have the default value an empty list.

def flat_it(values, result=list()):
    for v in values:
        if isinstance(v, list):
            flat_it(v, result)
        else:
            result.append(v)
    return result

x = [[1, 2, [3, 4, 5, 6, 7]], 4]
print x
print flat_it(x) 

 Thank you,
Bhargav.
 

     On Thursday, October 2, 2014 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


 
   


More information about the BangPypers mailing list