The Python Oracle

Python sorted lambda function returning a boolean

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Question
01:06 Accepted answer (Score 3)
02:32 Answer 2 (Score 2)
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/6484...

Accepted answer links:
[documentation]: https://docs.python.org/3.3/reference/ex...
[link]: https://docs.python.org/3/library/stdtyp...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sorting #lambda

#avk47



ACCEPTED ANSWER

Score 3


The reason is that:

x[0] in 'aeiou' 

returns 1 (or True) for ['anna', 'ollie'] and 0 (or False) for the rest. So 0 < 1, hence the output.

Do this instead:

print(sorted(a, key=lambda x: (x[0] not in 'aeiou', x)))

Output

['anna', 'ollie', 'bob', 'susan', 'tim', 'trevor']

For an explanation in comparisons, check the documentation, the quote below is from there:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Also for the behavior of Boolean values I suggest, the following link, quoting:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.




ANSWER 2

Score 2


When you are returning a boolean value, in python it corresponds True == 1, False == 0. So now when you sort your array, 0 is less than 1. That's why your are getting "anna" and "ollie" positioned last and rest of the names first.