1

When I use the sort() method on a list, then is affects the list permanently:

>>> numbers
[3, 1, 2]
>>> numbers.sort()
>>> numbers
[1, 2, 3]
>>> 

On the other hand, for example, when I use the strip() method on a string, then it doesn't affect the string permanently:

>>> string
' foo '
>>> string.strip()
'foo'
>>> string
' foo '
>>> 

Why is this so? Does it depend on simply how the method is built?

Martin
  • 957
  • 7
  • 25
  • 38

1 Answers1

2

Does it depend on simply how the method is built?

I guess you could say "yes", but the in-place methods - ones that have a "permanent" change - are usually found on mutable objects such as lists.

Mutable objects can change their value over their lifetime which means there isn't any point in returning a new object when these methods are called.

On the other hand, the methods that return a new object are for immutable objects. Immutable means the object has a fixed value and cannot change. Therefore, the in-place methods cannot work as they would need to alter the value of the object which isn't possible for immutable objects. This is why the methods return a new object, which is usually assigned back to the name that it was originally bound to, creating the effect of mutability, one could say.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21