Thread Shed Task 8 list modification question

I originally tried to do this task by stripping out the white-space, while maintaining the list of transactions that I had created using the below code:

daily_sales_replaced = daily_sales.replace(';,;', ':')
#print(daily_sales_replaced)

daily_sales_split = daily_sales_replaced.split(',')
#print(daily_sales_split)

transactions =[]
for transaction in daily_sales_split:
  transactions.append(transaction.split(':'))

for transaction in transactions:
  for item in transaction:
    item.strip()
print(transactions)

Can someone please explain why this won’t work. It leaves the transactions list unchanged. It seems redundant to constantly be having to create new lists.

I suppose you mean this loop doesn’t change the transactions list?

That’s because once you’ve used .strip() on each item, you don’t do anything with it. The .strip() method doesn’t modify the object in-place, it returns the modified object. That means, if you want a list of all the objects in the transactions list, but stripped of whitespace, you need to make use of the return value of .strip().


I can’t quite remember how the overall project works, but you could try replacing item with item.strip(). Something like this:

lst = [1,3,5,7]
for i in lst:
  lst[lst.index(i)] = i*2
print(lst)
#output: [2,6,10,14]

Note that it’s generally not considered good practise to modify the iterable that you’re iterating over.