consider the following code if insert() return the list itself.
def sieve(l):
if not len(l):
return []
return sieve(filter(lambda x: x%l[0] != 0, l)).insert(0, l[0])
For now, we have to rely on a helper function to return the list after insertion.
def cons(a, l):
l.insert(0, a)
return l
def sieve(l):
if not len(l):
return []
return cons(l[0], sieve(filter(lambda x:x%l[0] != 0, l)))
The point of mutable/immutable object is totally valid.
However, for lists that are mutable, IMHO, append() API could take one more step to return the list itself, rather than not returning anything. Java StringBuilder is a good example. I can do chained append on stringbuilder object recursively….Just wish we could have this here also.
In Python, it is a big deal to get beginners to learn which objects are “immutable” and cannot be changed, and which are “mutable” and can be altered — in the latter case, every reference to the object sees the same change. This really seems to confuse newcomers. “I innocently called this function I wrote, and suddenly my copy of the list is changed too!”
So Python has a convention: immutable objects, when you ask them to make an adjustment, return the newly-created object that is the answer — so:
makes
bget an entirely new string whileakeeps its original value. Obviously such methods must return a value, since you cannot see the change, ever, by inspecting the original, immutable object itself.But when you ask a mutable object to change itself, it does not return itself, because it does not need to — you can see the change just by looking at the original object again! This is a critical semantic signal in Python: if a method like
append()does not return a new object, then you can see the change just by looking at the old object, and so can everyone else with a reference to the old object.