Working with nested loops in python by keeping the inner list element as it is

Viewed 72

I have a nested loop that follows as below

arr = [[' item 1 ', 'item 2 ', 'item 3'], ['item 4  ', 'item 5', 'item 6'], ['item 7 ', 'item 8', 'item 9' ]]

I am trying to loop through the arr with 2 for loops to get rid of (strip) the spaces around each item in the inner loop. But when I use the following code, although I can get rid of the spaces, the final result only forms a combined list without the inner list elements intact.

clean_arr = []
for i in arr:
   for j in i:
      clean_arr.append(j.strip(' '))

The result I get is a single list without any inner lists/nested lists. But what I want is to keep the exact nested structure.

How can I achieve the result? Could you please put some discussion as well. Thanks

1 Answers

Try a list comprehension as follows:

clean_arr = [[y.strip() for y in x] for x in arr]
print(clean_arr)

Output:

[['item 1', 'item 2', 'item 3'], ['item 4', 'item 5', 'item 6'], ['item 7', 'item 8', 'item 9']]

If you want to use a for loop, try the below code:

clean_arr = []
for i in arr:
    l = []
    for j in i:
        l.append(j.strip())
    clean_arr.append(l)
Related