Stripping white space from a list within a list

Hello,

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

https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

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:
    transactions_clean.append(e.strip())

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.

1 Like

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

Consider,

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

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

2 Likes

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:

2 Likes