Say I wanted a simple method that takes a list
and modifies it in-place by appending 5
to it. Below are two methods that do this, but ret(l)
returns while no_ret(l)
does not.
def ret(l):
l.append(5)
return l
def no_ret(l):
l.append(5)
Which method is more pythonic? I'm guessing no_ret()
because if the method is for in-place modification, then there is no need to return since we already have a reference to the object being modified.
And how do they compare in terms of time and space efficiency?
- For time, I believe
ret(l)
is slower since the return statement adds additional overhead. - For space, I believe they are the same since
ret()
simply returns a reference (memory address) so no new memory is used.
I noticed that Python provides both the in-place non-returning instance method sort()
and non-in-place returning static method sorted()
. However I can't make my in-place methods to be instance methods of default classes like list
.