1

Must be missing something obvious, but why does this simple loop fail to modify the list items?

for artist in artists:
    artist = artist.replace(': ', '')

artists = [': Terence Trent D Arby', ": Guns N' Roses", ': Sinead O Connor' ...]

3 Answers 3

4

The loop control variable is just a local variable, referencing the elements of the list. If you re-assign that variable to any other object, it will no longer reference the original object in the list. So, assigning the artist to another object, doesn't make the reference in the list also to point to the new object.

To do what you want, you can create a new list with modified value, and assign it to original list reference. A list comprehension would be useful here:

artists = [artist.replace(': ', '') for artist in artists]
Sign up to request clarification or add additional context in comments.

4 Comments

I don't think "strings are immutable" has anything to do with it.
@arshajii. It has. If you have a list of list, then changing the list will be reflected in list of list. Of course, assigning the list reference to a new list, won't change the list of list.
I understand that, but the OP already seems to acknowledge the immutability of strings because he is reassigning in the first place. The reason he is not getting the expected result is due to the fact that reassigning the loop-control variable in a for-loop has no effect, as you just stated. I think that's what the question is really about.
I didn't downvote, but I imagine it's for the reason I stated.
1

Following statement just make artist to reference change value; this does not change list value.

artist = artist.replace(': ', '')

Try following code which use list comprehension:

artist = [artist.replace(': ', '') for artist in artists]

Comments

0

As Rohit said, artist is not a reference to the list item, so either you use a list comprehension, as suggested, which is the cleanest way IMO, either you do it "old school" like this, just to make you understand how it works behind the list comprehension Rohit gave you:

for index,artist in enumerate(artists):
    artists[index] = artist.replace(': ', '')

But I would do it this way:

artists = [artist[2:] for artist in artists]

ONLY if all you list items always start with ": " of course. Slicing might be faster than replacing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.