Python sorted lambda function returning a boolean
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle
--
Chapters
00:00 Python Sorted Lambda Function Returning A Boolean
00:42 Accepted Answer Score 3
01:55 Answer 2 Score 2
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/6484...
--
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.