Q:

How to modify list element within a for loop?

I'm trying to modify list elements and replace the original element with the newly modified one. However, I've noticed that the desired behavior differs depending on how I construct my for loop. For example:
samples = ['The cat sat on the mat.', 'The dog at my homework.']
punctuation = ['\'', '\"', '?', '!', ',', '.']

for sample in samples:
    sample = [character for character in sample if character not in punctuation]
    sample = ''.join(sample)

print(samples)

for i in range(len(samples)):
    samples[i] = [character for character in samples[i] if character not in punctuation]
    samples[i] = ''.join(samples[i])

print(samples)

This program outputs:
['The cat sat on the mat.', 'The dog at my homework.']
['The cat sat on the mat', 'The dog at my homework']

The second for loop is the desired output with the punctuation removed from the sentence, but I'm having trouble understanding why that happens. I've searched online and found this Quora answer to be helpful in explaining the technical details, but I'm wondering if it's impossible to modify list elements using the first method of for loops, and if I have to resort to using functions like range or enumerate to modify list elements within loops.
Thank you.

A:

Modifying the iterator is not enough,
You need to modify the list as well:

