[Tutor] operations on lists

Danny Yoo dyoo at hashcollision.org
Sat Apr 16 19:21:12 EDT 2016


On Wed, Apr 13, 2016 at 12:41 PM, marcus lütolf
<marcus.luetolf at bluewin.ch> wrote:
> Hello experts
>
> I'am working exercise 5. of 'Practical Programming 2nd edition, .....using Python 3'  (operations on lists).
> The following code get's me wrong results:
>
>>>> metals = [['beryllium', 4],['magnesium', 12], ['calcium', 20], ['strontium', 38], ['barium', 56], ['radium', 88]]
>>>> max(metals)
> ['strontium', 38]
>>>> min(metals)
> ['barium', 56]


When comparing list structures, Python uses a lexicographic ordering.
http://mathworld.wolfram.com/LexicographicOrder.html



> It should return
> ['radium', 88] and
> ['beryllium', 4] respectively


If you want this, you have to tell Python not to use its default
lexicographic ordering.

See: https://wiki.python.org/moin/HowTo/Sorting.  In particular, pay
special attention to the section here:
https://wiki.python.org/moin/HowTo/Sorting#Key_Functions, because it's
very relevant to your question.


If you have questions, please feel free to ask!


More information about the Tutor mailing list