Double for loop list comprehension

ghz 昨天 ⋅ 0 views

I am trying to do following operation using list comprehensions:

Input: [['hello ', 'world '],['foo ',' bar']]
Output: [['hello', 'world'], ['foo', 'bar']]

Here is how one can do it without list comprehensions:

a = [['hello ', 'world '],['foo ',' bar']]
b = []

for i in a:
   temp = []
   for j in i:
      temp.append( j.strip() )
      b.append( temp )

print(b)
#[['hello', 'world'], ['foo', 'bar']]

How can I do it using list comprehensions?

Answer

You can use list comprehensions to achieve this as follows:

a = [['hello ', 'world '],['foo ',' bar']]
b = [[j.strip() for j in i] for i in a]

print(b)
# Output: [['hello', 'world'], ['foo', 'bar']]

This applies the strip() method to each string in the inner lists and creates the desired output in one line.