[Tutor] 'in-place' methods

Kent Johnson kent37 at tds.net
Sat Feb 18 03:13:19 CET 2006


Michael Broe wrote:
> I think I understand this sorting-a-list 'in place' stuff, and things  
> of that kind (reversing for example); but I am finding it very  
> difficult to get used to, since sorting a list doesn't return the  
> sorted list as a value, but simply does the work as a side effect.
> 
> The place where it really trips me up is when I want to do something  
> like pass a sorted list as a value in a program, say.
> 
> Anyway, first question: is the fact that the first doesn't work  
> purely a function of the fact that lists are mutable? (At least I  
> could kind of understand that, that methods work differently for  
> objects of different types). Or is it possible to have methods  
> like .upper() that return the result of performing the operation even  
> for lists?

list.sort() certainly could have been written to return the list as well 
as sort in place. It was an intentional design decision not to do this - 
mutating methods all return None by choice. I think the reasoning is

- The current situation causes errors when you think the mutating 
methods will return the object being mutated, but instead they return 
None. These errors show up quickly and are easily found.

- If the mutating methods also returned a value, it would be possible to 
write code thinking that they are *not* mutating - for example your 
attempt to print a sorted list - but this code would have subtle side 
effects that could lead to hard-to-find bugs.

I think I have that right...

Ruby has an interesting approach to this - the names of mutating methods 
end with !. So it would be list.sort!() which gives a strong cue to what 
is happening.

Kent



More information about the Tutor mailing list