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

Joel Goldstick joel.goldstick at gmail.com
Sun Sep 2 22:01:38 EDT 2018


On Mon, Sep 3, 2018 at 1:50 PM C W <tmrsg11 at gmail.com> 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.
>
> Example 2:
> > name = "John Smith"
> > name.replace("J", j")
> > name
> 'John Smith'
> This does not change the original string.
>
> Why the two examples produce different results? As a beginner, I find this
> confusing. How do you do it?
>
> Thank you!
> --
> https://mail.python.org/mailman/listinfo/python-list

Learn about help.  Go to python command line and type help(L) it will show that
 this method reverses in place.  Type help(name) and it will show that this
method returns the result, but does not change your list.

--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays




More information about the Python-list mailing list