ok, noob question
I had this code
list = ['random', 'set', 'of', 'strings']
for item in list:
item.replace('a','b')
print list
the output doesn’t show the replacement unless I change the code to this
list = ['random', 'set', 'of', 'strings']
for item in list:
item = item.replace('a','b')
print list
so my question is what exactly is going on? why doesn’t the first example automatically assign?
The method is simply returning the new value, it does not modify the existing one.
There is no set rules that specify that all or no methods will do this, you will have to check the documentation for each one to know specifically what it does and what to expect.
Lots of functions are like that.
Take this:
would you expect a or b to have new values at this point? This is the same exact thing.
Now, having said that, there is another problem with your code. Under no circumstances will that list actually change.
Why? Because you’re not updating the list, you’re updating item.
And item is a “copy” of the value in the list. This is not strictly correct, but it suffices for this answer (learn about references for more information.)
In other words, if you change your two examples to this:
vs.
then you will see a difference.
Answer to follow-up question in comment: If you do not store the result anywhere, it is simply lost. Think of it this way: You call up your friend and ask what time it is on his watch. He says “10:45”, and you respond with “actually I don’t care click.”