[Tutor] 'in-place' methods

Michael Broe mbroe at columbus.rr.com
Fri Feb 17 22:57:08 CET 2006


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.

Here is a trivial example. Say I want to define a function to always  
print lists in sorted form. I can't do it as follows, tho it's what I  
want to do intuitively:

def sort_print(L):
	print L.sort()
	
This is on a strict analogy to writing a function that prints strings  
in upper case only:

def upper_print(s):
	print s.upper()
	
(The fact that the second works and the first doesn't really does bug  
me as a newbie.)

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?

Second question. Do I really have to write the sort_print() function  
like this:

def sort_print(L):
	L.sort()
	print L
	
i.e. first perform the operation in-place, then pass the variable? Is  
this the idiomatic way of doing it?

Third question: is this in-place behavior of methods in effect  
restricted to lists, or are there other places I should be on the  
lookout for it?

Cheers,
Mike




More information about the Tutor mailing list