[Tutor] (no subject)
Magnus Lycka
magnus@thinkware.se
Wed, 02 Oct 2002 15:52:16 +0200
At 10:48 2002-10-02 +0200, Annika Scheffler wrote:
>Hi Rob,
>
>Thanks for your help! In fact, it does work that way for me, too. But when
>writing a function like this:
>
>def sortList(someList):
>
>
> return someList.sort()
>
>print sortList("What have we here".split())
>
>I get "none" as a result. Why's that?
Same reason as
a =3D someList.sort()
print a
None
The statement "return someList.sort()" means:
"Please python, would you return the return
value of the sort() operation on the someList
object to the calling function?"
.sort() changes the list it sorts. It doesn't
return any value. You need to return the sorted
list, not the non-existing return value of the
sort operation.
You need
def sortList(someList):
someList.sort()
return someList
Contrast this with
a =3D someList.index(5)
or
return someList.count('x')
In these cases we use list operations that actually
return a value we care about.
The reason why sort() and reverse() chages the list
instead of returning a sorted/reversed list, leaving
the original unchaged, is that the list might be very
big, and the return value will be equally big. This
might use up more memory than you care for.
If you need to keep the sorted list intact, you can
change your function to:
def sortList(someList):
sorted =3D someList[:]
sorted.sort()
return sorted
Please note that the first version changes the
"original" list.
If you type
a =3D [1,2,3,4]
b =3D a
then both a and b will refer to the _same_ list.
Not two identical.
b.reverse()
print a
[4, 3, 2, 1]
--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se