Kirill
Kirill

Reputation: 77

Iterating through list of lists

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)

Upvotes: 2

Views: 23159

Answers (4)

blhsing
blhsing

Reputation: 107134

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]

Upvotes: 5

DocDriven
DocDriven

Reputation: 3974

This solution works for any list depth:

orig = [[' a', 'b '], ['c ', 'd '], ['e ', ' f']]

def worker(alist):

    for entry in alist:
        if isinstance(entry, list):
            yield list(worker(entry))
        else:
            yield entry.strip()

newlist = list(worker(orig))

print(orig)
print(newlist)

Upvotes: 1

hod
hod

Reputation: 761

Try this:

org = [ [' a ','b '],['c ',' d '],['e ',' f'] ]
new = []
temp = []

for o in org:
    for letter in o:
        temp.append(letter.strip())
    new.append(temp)
    temp = []

Result:

[['a', 'b'], ['c', 'd'], ['e', 'f']]

Hope this helps!

Upvotes: 2

user10340130
user10340130

Reputation:

Something like -

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

Upvotes: 4

Related Questions