0

I have a list of lists like

mylist = [[' a', ' b'],[' a', ' b', ' c'],[' a', ' c']]

I want to remove all spaces, I tried the below, but it then lists all items into one list ['a', 'b', 'a', 'b', 'c', 'a', 'c'], while I want to preserve list of lists.

mylist2 = []
for i in mylist:
    for j in i:
        k = j.replace(' ','')
        mylist2.append(k)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
haven
  • 1
  • 3
  • Simply use [`str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip). For example: `" a".strip(" ")`. There is also [`str.lstrip`](https://docs.python.org/3/library/stdtypes.html#str.lstrip) and [`str.rstrip`](https://docs.python.org/3/library/stdtypes.html#str.rstrip) – Thomas Oct 18 '21 at 23:50
  • 1
    Dupe [Python: Removing spaces from list objects](https://stackoverflow.com/questions/3232953/python-removing-spaces-from-list-objects) – chickity china chinese chicken Oct 18 '21 at 23:52
  • @Thomas could you suggest how to do it in a for loop? `strip` is not an attribute of list. – haven Oct 19 '21 at 00:47
  • @chickitychinachinesechicken yes, that's where I got the loop idea, but that's a list example, I'm struggling with a list of lists. – haven Oct 19 '21 at 00:47
  • @chickitychinachinesechicken this would work for a list, but doesn't work in this case. – haven Oct 19 '21 at 01:28
  • the result is a list of lists: `[['a', 'b'], [' a', 'b', 'c'], ['a', 'c']]` that you mentioned in the question you want that preserved. – chickity china chinese chicken Oct 19 '21 at 01:32
  • What is the output you require? – chickity china chinese chicken Oct 19 '21 at 01:32
  • @chickitychinachinesechicken `[['a', 'b',], ['a', 'b', 'c'], ['a', 'c']]` so all spaces before a letter removed. If I run the code I used, the structure breaks and I end up with 1 list instead of a list of lists. – haven Oct 19 '21 at 01:36
  • try: `cleanlist = [[i.strip(' ') for i in l] for l in mylist]` , should give that same result – chickity china chinese chicken Oct 19 '21 at 01:43

0 Answers0