[Tutor] Using sorted in Python 3.3.5

Alan Gauld alan.gauld at btinternet.com
Thu Nov 19 13:31:03 EST 2015


On 19/11/15 15:31, Greg Christian wrote:
> I’m trying to sort a list of tuples based on the second item in the tuple. When I run this in IDLE I get the correct output; however, when running inside of a program, and calling the counter() function, sorted does not seem to work? Any ideas on why this works in IDLE and not in program would be appreciated. Thank You.
>
> def getKey(item):
>      return item[1]
>
> def counter():
>      L = [("baby", 9999), ("aeuron", 100), ("pablo", 1234)]
>      sorted(L, key=getKey)
>      print ("L = ", L)
>
> OUTPUTS THIS (when calling counter inside of program):
>
> L =  [('baby', 9999), ('aeuron', 100), ('pablo', 1234)]
>

sorted() returns the soirted collection, it does not sort it in place.
If you want in-place use the sort method.


> OUTPUTS THIS (when running with IDLE – desired output):
>
> [('aeuron', 100), ('pablo', 1234), ('baby', 9999)]

I'm not sure why IDLE does that.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list