Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I wonder whether there is a shortcut to make a simple list out of the list of lists in Python.

I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with reduce, but I get an error.

Code

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] 

reduce(lambda x, y: x.extend(y), l)

Error message

Traceback (most recent call last): 

File "<stdin>", line 1, in <module> 

File "<stdin>", line 1, in <lambda> 

AttributeError: 'NoneType' object has no attribute 'extend'

1 Answer

0 votes
by (106k points)

To make a flatten list python you can use the following ways:-

flat_list = [item for sublist in l for item in sublist]

Which means:

flat_list = [] 

for sublist in l: 

     for item in sublist: 

         flat_list.append(item)

Related questions

0 votes
1 answer
asked Sep 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
+3 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...