-3

I have the following code:

list1 = [['a','b','c'],['d','e','f'],['g','h','i']]
sentences = []
for row in list1:
    for i in row:
        sentences.append(i)

print(sentences)

With the output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

How can I write that in one sentence? This is what I tried:

sentences = [i for i in row for row in list1]
print(sentences)

This is what I got:

['g', 'g', 'g', 'h', 'h', 'h', 'i', 'i', 'i']
Timo Vossen
  • 303
  • 2
  • 3
  • 10

4 Answers4

2

Just need to give your list comprehension a switch in order.

sentences = [i for row in list1 for i in row ]
print(sentences)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Correy Koshnick
  • 211
  • 1
  • 8
2

You need to make the loop correct

[j for i in list1 for j in i]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Note: If the loop goes like

for b in a:
    for c in b:
        for d in c:
            ...

In list comprehension, it goes like

[... for b in a for c in b for d in c]
Epsi95
  • 8,832
  • 1
  • 16
  • 34
2

x being the matrix

x = [['a','b','c'],['d','e','f'],['g','h','i']]

 [val 
     for sublist in x 
        for val in sublist] 

The first line suggests what we want to append to the list. The second line is the outer loop and the third line is the inner loop.

kiranr
  • 2,087
  • 14
  • 32
2
list1 = [['a','b','c'],['d','e','f'],['g','h','i']]
a =[i for row in list1 for i in row]
print(a)

Just swap the order

Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25