I'm practicing for my exam and there are always questions asking whether a method changes an object in place or creates a new object. I wonder if there are any general rules applied to this or if I just have to memorise the outcome for different methods?

The examples from my exam are:

s = 'horse'
s.upper()
print(s)

this will generate horse and not HORSE, and thereby s is not changed by .upper, however

l = [1, 3, 2]
l.sort()
print(l)

will generate [1, 2, 3] and not [1, 3, 2], and thereby l is changed by .sort

Are there any ways to differentiate between these?

1 Answers

1
deceze On

There are no real generic ways to remember this. You need to remember on an individual basis. You can generally remember that strings are immutable and never change. And you can specifically remember that the .sort method explicitly returns None to remind people that it sorts in place, and that you need to use the sorted() function if you want a copy instead. But those are specific to strings and sorting, knowing this doesn't help you to generalise at all.

Generally speaking, such knowledge simply accumulates with usage. In practical everyday programming, nobody needs to know this by heart, since you'll always be thumping the documentation while you're coding and/or you'll try small snippets on the interactive command line to confirm their workings. Learning this by rote for a test has no practical purpose in later use; likely you're supposed to remember the few types and functions that were explicitly mentioned in your lessons, if you're presented with a heretofore unknown type, your guess will be as good as mine.