[Tutor] 'in-place' methods

Brian van den Broek broek at cc.umanitoba.ca
Sat Feb 18 13:04:28 CET 2006


Michael Broe said unto the world upon 17/02/06 03:57 PM:

<snip>

> 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?

Hi Michael,

others have answered what you asked; I thought I'd try to head off a 
potential problem for you.

Perhaps you've seen this already, but since you are wrapping the print 
in a function, I suspect you want the original list to be unmodified. 
Thus, compare:

 >>> def sort_print1(a_list):
	a_list.sort()
	print a_list

	
 >>> def sort_print2(a_list):
	t = list(a_list)
	t.sort()
	print t

	
 >>> list1 = ["sort_print1", "mutates", "the", "original"]
 >>> list2 = ["sort_print2", "doesn't", "mutate", "the", "original"]
 >>> sort_print1(list1)
['mutates', 'original', 'sort_print1', 'the']
 >>> list1
['mutates', 'original', 'sort_print1', 'the']
 >>> sort_print2(list2)
["doesn't", 'mutate', 'original', 'sort_print2', 'the']
 >>> list2
['sort_print2', "doesn't", 'mutate', 'the', 'original']
 >>>

HTH,

Brian vdB


More information about the Tutor mailing list