Search code examples
pythonfunctional-programmingimmutabilityconventionsmutable

Python methods: modify original vs return a different object


I'm new to Python and object orient programming, and have a very basic 101 question:

I see some methods return a modified object, and preserve the original:

In: x="hello"
In: x.upper()
Out: 'HELLO'
In: x
Out: 'hello'

I see other methods modify and overwrite the original object:

In: y=[1,2,3]
In: y.pop(0)
Out: 1
In: y
Out: [2, 3]

Are either of these the norm? Is there a way to know which case I am dealing with for a given class and method?


Solution

  • Your examples show the difference between immutable built-in objects (e.g., strings and tuples) and mutable objects (e.g., lists, dicts, and sets).

    In general, if a class (object) is described as immutable, you should expect the former behavior, and the latter for mutable objects.