[Tutor] 'in-place' methods

w chun wescpy at gmail.com
Sat Feb 18 00:06:19 CET 2006


hi mike,

welcome to python.  :-)  your query is quite common amongst beginners,
and i have actually spend some time on this topic in my courses.

On 2/17/06, Michael Broe <mbroe at columbus.rr.com> 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.
>
> def sort_print(L):
>         print L.sort()
>
> 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.)

as i hinted to above, this confusion happens quite regularly.

> Anyway, first question: is the fact that the first doesn't work
> purely a function of the fact that lists are mutable?

this is the primary reason.  the side effect is also a reason why the
sorted() BIF (built-in function) was added to Python.


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

if using sorted() doesn't work for you, then yes.


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

since most all other Python types are immutable, no in-place
operations can occur, so this is not an issue.

and altho dictionaries are Python's other mutable type (ignoring sets
at the moment), ordering isn't a feature of hashes/mapping types, so
no one gets bitten there either.

hope this helps... a little!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2006,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list