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

Chris Angelico rosuav at gmail.com
Mon Sep 3 12:08:10 EDT 2018


On Tue, Sep 4, 2018 at 3:49 AM, 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?

A very fair question.

Firstly, strings are immutable. Once you have a string, nothing can ever change
 it. Lists, on the other hand, can change (you can append to them, remove
elements, etc, etc). So reversing a string in-place is impossible, but it's an
option for the list.

Secondly, you get a clue from the return values.

>>> L = [3, 6, 1,4]
>>> L.reverse()
>>> L
[4, 1, 6, 3]
>>> name = "John Smith"
>>> name.replace("J", "j")
'john Smith'
>>> name
'John Smith'

Notice how name.replace() returns the new string, but L.reverse() doesn't
return anything? (Technically it returns None, but that's used as a signal
meaning "I got nuffin, govna!".) That's a strong clue; if something sounds like
 it ought to make a change, but it returns None, it's almost certainly changed
the object in-place.

If you like, you can iterate backwards over the list, rather than actually
reversing it:

for number in reversed(L): ...

And you can use a very convenient, if a little obscure, syntax to create a
reversed copy of the list:

>>> L
[4, 1, 6, 3]
>>> L[::-1]
[3, 6, 1, 4]

(So you can assign that to another name, or whatever.) This is called "slicing"
 the list, if you want to look it up in the docs.

Ultimately, your question comes down to the difference between mutable and
immutable types. Definitely something worth learning more about, and definitely
 worth asking these sorts of questions about.

Thanks for asking! :)

ChrisA




More information about the Python-list mailing list