Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through list of lists

Tags:

python

list

i have list of lists, i need via Python iterate through each string ,remove spaces (strip) and save list into new list.

E.g. original list: org = [ [' a ','b '],['c ',' d '],['e ',' f'] ]

Expecting new list: new = [ ['a','b'],['c','d'],['e','f'] ]

I started with below code, but no idea how to add stripped objects into new list of lists. new.append(item) - create simple list without inner list.

new = [] for items in org: for item in items: item= item.strip() new.append(item)

like image 518
Kirill Avatar asked Nov 21 '25 14:11

Kirill


1 Answers

You can use a nested list comprehension that strips each word in each sub-list:

new = [[s.strip() for s in l] for l in org]
like image 158
blhsing Avatar answered Nov 24 '25 06:11

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!