PCEP-30-02 · Question #27
What is the expected output of the following code? ``python 1 data = ['abc', 'def', 'abcde', 'efg'] 2 print(max(data)) ``
The correct answer is A. efg. When max() is called on a list of strings, Python compares them lexicographically (like dictionary order, character by character using Unicode values), so it returns whichever string would appear last alphabetically - and 'efg' wins because 'e' is the highest first character…
Question
1 data = ['abc', 'def', 'abcde', 'efg']
2 print(max(data))
Options
- Aefg
- Babc
- Cdef
- DThe code is erroneous.
- Eabcde
- FNone of the above.
How the community answered
(37 responses)- A78% (29)
- B5% (2)
- C3% (1)
- D11% (4)
- F3% (1)
Explanation
When max() is called on a list of strings, Python compares them lexicographically (like dictionary order, character by character using Unicode values), so it returns whichever string would appear last alphabetically - and 'efg' wins because 'e' is the highest first character among all four strings.
Options B ('abc') and E ('abcde') are wrong because both start with 'a', which ranks below 'd' and 'e'; the extra length of 'abcde' does not help since comparison stops as soon as a differing character is found. Option C ('def') starts with 'd', which is less than 'e', so it loses to 'efg'. Option D is wrong because the code runs without error - max() works perfectly on a list of strings.
Memory tip: Think of max() on strings as asking "who comes last in a dictionary?" - whichever string would be shelved furthest toward 'z' wins, and comparison always starts at the first character.
Community Discussion
No community discussion yet for this question.