[BangPypers] Python List Comprehension Question

Rajiv Subramanian M rajiv.m1991 at gmail.com
Thu Oct 2 12:21:41 CEST 2014

Hello Group,

I'm Rajiv working as web developer in bangalore.

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 += 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]

please help.


  [image: --]
Rajiv Subramanian M
[image: http://]about.me/rajiv.m1991

More information about the BangPypers mailing list