Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to convert a list of lists into a flat list with Python

5 Answers

0 votes
def convert(lst_lst): 
    for i in lst_lst: 
        if type(i) == list: 
           convert(i) 
        else: 
           lst.append(i) 
   
 
lst_lst = [1, 2, 3, [7, 4, [0, 1]], 9, [6, [8], 15]] 
 
lst = [] 
convert(lst_lst) 
print(lst)
 
  
 
'''
run:
 
[1, 2, 3, 7, 4, 0, 1, 9, 6, 8, 15]
 
'''

 



answered Dec 22, 2019 by avibootz
edited Jan 27, 2020 by avibootz
0 votes
lst_lst = [[1, 2, 3] ,[4, 5, 6], [7, 8, 9]]

lst = sum(lst_lst, [])
 
print(lst)
 
 
 
'''
run:
 
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
'''

 



answered Jan 27, 2020 by avibootz
0 votes
from functools import reduce

lst_lst = [[1, 2, 3] ,[4, 5, 6], [7, 8, 9]]
 
lst = reduce(lambda x,y: x+y, lst_lst)
  
print(lst)
  
  
  
  
'''
run:
  
[1, 2, 3, 4, 5, 6, 7, 8, 9]

'''

 



answered Mar 18, 2023 by avibootz
0 votes
import numpy as np

lst_lst = [[1, 2, 3] ,[4, 5, 6], [7, 8, 9, 10, 11]]

lst = list(np.concatenate(lst_lst))

print(lst)
  
  
  
  
'''
run:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

'''

 



answered Mar 18, 2023 by avibootz
0 votes
import operator
from functools import reduce
 
lst_lst = [[1, 2, 3] ,[4, 5, 6], [7, 8, 9, 10]]
  
lst = reduce(operator.concat, lst_lst)
   
print(lst)
   
   
   
   
'''
run:
 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
'''

 



answered Mar 18, 2023 by avibootz

Related questions

1 answer 130 views
1 answer 230 views
2 answers 202 views
1 answer 133 views
2 answers 213 views
...