1

I've gotten this function to work without list comprehension, however, I was wondering how to do it with one:

def flatten(L): 
    a_list = [] 

    for i in L: 
        if isinstance(i, list): 
            gl = flatten(i) 
            for n in gl: 
                a_list.append(n)

        else: 
            a_list.append(i) 

    return a_list 

    #  This is how I've attempted to use list comprehension, but I get a Syntax
    #  error and I'm not sure why.

    return [n for n in flatten(i) if isinstance(i, list) else i for i in L] 
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
user2690972
  • 131
  • 1
  • 1
  • 12

1 Answers1

2

The syntax error can be fixed, you've got wrong precedence, you need parentheses:

return [(n for n in flatten(i)) if isinstance(i, list) else i for i in L]

This, unfortunately, won't do what you would like to do and it's impossible to do with one list comprehension.

List comprehensions generate one result per input (it's like a map operation), so you cannot generate a list which is larger than the original, which is necessary for flattening.

Look for alternative solutions here: Flatten (an irregular) list of lists

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Oh crap does that work? I didn't think you could use else statements to change the whole list comp, only the value! That's amazing! – Adam Smith Jan 25 '14 at 22:04
  • Yeah, your solution adds generators to the list. However, thanks a lot for the insight! I was skeptical whether I could do it in one comprehension. I'll try to figure out a more efficient way, if its possible. – user2690972 Jan 25 '14 at 22:17