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,948 questions

51,890 answers

573 users

How to convert a 2D list to a 1D list in Python

2 Answers

0 votes
def list2d_to_1d(list2d):
    lst = []
    
    for i in range(len(list2d)):
        for j in range(len(list2d[i])):
            lst.append(list2d[i][j])
    
    return lst

list2d = [
        [5, 6, 1],
        [3, 8, 0],
        [9, 2, 7]
    ]

lst = list2d_to_1d(list2d)

for n in lst:
    print(n, end="\t")



'''
run:

5	6	1	3	8	0	9	2	7

'''

 



answered Aug 14, 2024 by avibootz
0 votes
import itertools
 
list2d = [
        [5, 6, 1],
        [3, 8, 0],
        [9, 2, 7]
    ]
 
lst = list(itertools.chain.from_iterable(list2d))

for n in lst:
    print(n, end="\t")
 
 
 
'''
run:
 
5	6	1	3	8	0	9	2	7
 
'''

 



answered Aug 14, 2024 by avibootz

Related questions

1 answer 145 views
1 answer 75 views
2 answers 143 views
1 answer 78 views
1 answer 90 views
...