Why list.reverse() modifies the list, but name.replace() does not modify the string?
Yes, I forgot that strings are immutable. I can't change anything in the string. Silly me!
Thank you very much, I appreciate it. I guess sometimes it just take an outsider to take you outside the box. And all is answered. :)
From: Python-list <python-list-bounces+tmrsg11=gmail.com at python.org> on behalf of Mark Lawrence <breamoreboy at gmail.com>
Sent: Monday, September 3, 2018 2:21:36 PM
To: python-list at python.org
Subject: Re: Why list.reverse() modifies the list, but name.replace() does not modify the string?
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]
> [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")
> '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.