Stripping white space from a list within a list


I’m going through the Python 3 course, and I got to the “Thread Shed” project under the strings section.

I’m stuck on task 8, where it asks me to clean up the strings within a list which is, itself, within another list.

My code:

transactions_clean = []
for i in daily_transactions_split:
  for e in i:

The above creates a new list with all the strings stripped of white space. But it gets rid of the original lists within the list. I would like to keep the original structure intact, but with cleaned internal list.

Must’ve spent 2 hours trying to figure this out. So help would be very much appreciated.


Please review How do I format code in my posts?

1 Like

Thanks for the response. The post is now formatted correctly.

1 Like

So, consider what is happening. You take each element of a list which is also a list, then you iterate though the elements of that list, strip the white space, and append them to the new list.

What you are wanting to do is strip the white space from each element inside the nested list, and then append the entire list to the new list, so that you end up with a list of lists like you originally had.

Do you see the difference in what I wrote? The second part includes some extra steps. Consider how you could make changes to each element of the nested list, and then append the list.


I think what Tod is pointing out is that statement should not be inside the inner loop.


for row in daily_transactions_split:
    for col in range(len(row)):
        row[col] = row[col].strip()

Notice that in the inner loop all we do is mutate each element and assign it back to the same list?


Thanks a lot guys. It seems obvious now that I see the solution. But I couldn’t for the life of me figure it out on my own. :slight_smile:


I am having the same issue but can somebody again explain this? I am not quite sure I understand this.


It took a few mins to figure out what mtf said, but it basically means below:

My original codes:

transactions_clean = [] for transaction in daily_transactions_split: for data in transaction: data_clean = data.strip() transactions_clean.append(data_clean)

It turns out adding all transaction data in one single list, instead to returning the original nested list structure.

The solution is following:

transactions_clean = [] for transaction in daily_transactions_split: for i in range(len(transaction)): transaction[i] = transaction[i].strip() transactions_clean.append(transaction)

The keys are:
1/ Strip and replace the transaction data directly by
“transaction[i] = transaction[i].strip()” in the second for loop
2/ Append the whole transaction (instead of each transaction data) into the “transaction_clean” list. This is done by appending under first for loop instead of second for loop

Hope above helps!

1 Like