Why list.reverse() modifies the list, but name.replace() does not modify the string?

Mark Lawrence breamoreboy at gmail.com
Mon Sep 3 14:21:36 EDT 2018


On 03/09/18 18:49, C W wrote:
> Hello all,
> 
> I am learning the basics of Python. How do I know when a method modifies
> the original object, when it does not. I have to exmaples:
> Example 1:
>> L = [3, 6, 1,4]
>> L.reverse()
>> L
> [4, 1, 6, 3]
> This changes the original list.

Lists are mutable, i.e. can be changed, so it makes sense to do this 
change in place.

> 
> Example 2:
>> name = "John Smith"
>> name.replace("J", j")
>> name
> 'John Smith'
> This does not change the original string.

Strings are immutable, i.e. cannot be changed, so you have to create a 
new string.  Your call to `replace` will do just that, but as it's not 
saved `name` remains the same.  You could use

name = name.replace("J", j") or

newname = name.replace("J", j") as you see fit.

> 
> Why the two examples produce different results? As a beginner, I find this
> confusing. How do you do it?
> 
> Thank you!
> 


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list