-1

I have the impression this snippet can be improved with list comprehension and a function based on the answers related. Then, I proceeded to changed this snippet:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
flat_list = []
for sublist in l:
    print("sublist: ", sublist)
    for item in sublist:
        if type(item)== list:
            for i in item:
                flat_list.append(i)
        else:
            flat_list.append(item)

print(flat_list)

To this new version which is not working:

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]

def foo(item):
    flat_l=[]
    if type(item)== list:
        for i in item:
            flat_l.append(i)
    else:
        flat_l.append(item)

    return flat_l

flat_list=[item for sublist in l foo(item) for item in sublist]

print(flat_list)

Which is complaining due to syntax error:

File "", line 33 flat_list=[item for sublist in l foo(item) for item in sublist] ^ SyntaxError: invalid syntax

John Barton
  • 1,581
  • 4
  • 25
  • 51
  • Note that lists have an extend method. There There is no need to iterate-and-append as in the first if branch. – MisterMiyagi Oct 09 '19 at 19:16
  • Possible duplicate of [How to make a flat list out of list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – b_c Oct 09 '19 at 19:17
  • 2
    Yeah, there's a syntax error precisely where it pointed out. `l foo` is just two identifiers next to each other. – Yann Vernier Oct 09 '19 at 19:20
  • Possible duplicate of [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – mayosten Oct 09 '19 at 19:25

1 Answers1

0

my code in python3

l=[['rfn'], ['abod'], [['splash', 'aesthet', 'art']], [['splash', 'aesthet', 'anim']], ['fabl'], ['clean']]
e=[]
any(e.extend(i[0]) if isinstance(i[0], list) else e.extend(i) for i in l)
print(e)
  • This works for this particular example but for `[[['abc']]]` it outputs `[['abc']]` (which is not a flat list) and for `[[['abc'], 'def']]` it outputs `['abc']`. Please provide more explanation what your code does, so that others understand when to use it and when not to use it. – BurningKarl Oct 09 '19 at 21:13
  • yes but according to the example your need is not the need of the author. – Narcisse Doudieu Siewe Oct 10 '19 at 00:04