[Tutor] Using sorted in Python 3.3.5

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Nov 19 13:33:46 EST 2015


On 19/11/2015 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)]
>
> OUTPUTS THIS (when running with IDLE – desired output):
>
> [('aeuron', 100), ('pablo', 1234), ('baby', 9999)]


Your use of sorted achieves precisely nothing as you discard the return 
value.  Either save the value or use the built-in sort which works in place.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list