Thread Shed Python: step 8

In step 8 I want to compare the two following codes

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

The second code returned the correct answer for step 8 since all the white spaces in all the elements within the sub-lists get stripped, while the first code didn’t. I don’t really see the difference between the two since both iterate through all the elements within the sub-lists, strip white spaces, reassign the formatted string back to the temporary variable, and then append the sub-lists to the transaction_clean list. There is definitely something wrong with my current logic and understanding of lists and loops, but I don’t see it yet, so help is much appreciated.

If you’re ever uncertain how a loop is iterating there’s nothing wrong with just firing print statements in there to see what’s what.

I think what you’re arguably missing is something more along the lines of understanding mutable datatypes and assignment (mutability isn’t discussed much so that’s fair enough).

As it stands you could rewrite that first snippet in the following way and your final values would be exactly the same as if you left that for loop in there-

transactions_clean = []
for transaction in daily_transactions_split:
  transactions_clean.append(transaction)
print(transactions_clean)

As for why-
i.strip() creates a new string with the trailing whitespaces removed. i = i.strip() assigns the reference of that new string to a name i. Whatever i referred to before is ignored.

This is similar to-

x = 3
x = 5  # whatever x referred to before doesn't matter
print(x)
Out: 5

transaction[i].strip() also creates a new string object with trailing whitespace removed. However transaction[i] = is effectively relabelling the reference that used to be held at the i th index of transaction. You modify transaction itself so that by the time that inner loop finishes the references it holds have all been changed and you can .append those changes to your new cleaned up list-transactions_clean.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.