Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Logen Li
Courses Plus Student 1,276 PointsPython 2 D list
Hey Guys! Just wonder how python max() function works? I know for character and number. But what about word?
e.g.
LOL =[["Feb",5],["God",6],["Huf",2],["Boy",9],["Girl",10]] ---- 2D list max(LOL)
LOL = ["Nothing","is","Bad"] -- Word max(LOL)
I know the result but confused about how python max() function find the answer.
2 Answers
Eric M
11,547 PointsHi Logen,
String comparison in Python (and a number of other languages) is based on the value of the ASCII characters making up that string. When working with strings max() will show you the string that starts with the highest (ASCII) value character. If two strings start with the same (highest value) character it will from those return the string with the highest second character, and so on.
In your second example you have strings starting with N, B, and i. Their ASCII values are:
'N' = 78
'B' = 66
'i' = 105
max() will return the string starting with i as it has the highest value.
It is possible to write your own sorting algorithm that compares strings on some other quality. Check out the Computer Science courses here on Treehouse if this is something that interests you c:
Cheers,
Eric
Logen Li
Courses Plus Student 1,276 PointsThank you Eric! Your information is very very helpful!
Logen Li
Courses Plus Student 1,276 PointsLogen Li
Courses Plus Student 1,276 PointsHi Thank you!
It is very clear.
But for the first (2D array). The compiler return "Huf",2. It worked without a sorting algorithm So I just wonder does python evaluate it based on the word or the number?
Eric M
11,547 PointsEric M
11,547 PointsHi Logen,
There is already a built in sorting algorithm working in the background to compare things :) Luckily we do not have to write this (or many other things) ourselves.
The reason why the first array returns its result is the same as the second. The first item of each iterable is compared, then the first sub-item, on an on, until the highest one is found.
["Huf", 2] starts with a higher value (72) than any of the other lists start with, so it is returned by
max().Cheers,
Eric