Why this behavior? (was: Stupid Lambda Tricks)

Simon Brunning SBrunning at trisystems.co.uk
Thu Feb 21 07:29:49 EST 2002


> From:	Jonathan Gardner [SMTP:jgardn at alumni.washington.edu]
> I've always wondered:
> 
> >>> "abc".upper()
> "ABC"
> >>> [3,1,2].sort()
> < nothing >
> 
> Why is that? Is it just easier to implement it this way, or is there some 
> sound philosophical reason for this?
 
The latter.

Strings are immutable, so methods which 'change' them must in fact be
creating a new string. This has to be returned by the method - otherwise,
where would it go?

Lists are mutable. Methods actually *do* change them - 'sort' sorts the list
in place. To remind you of this fact, nothing is returned by the method. If
'sort' *did* return the sorted list, you could do:

spam = [3, 2, 1]
eggs = spam.sort()

Now, you might think that eggs is sorted and spam isn't, but if fact, spam
*is* sorted.

So instead, sort returns nothing, and you'll get a runtime error of some
sort in no time, and you'll find the problem quickly.

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.




More information about the Python-list mailing list