I have a list which contains strings representing animal names. I need to sort the list. If I use sorted(list)
, it will give the list output with uppercase strings first and then lowercase.
But I need the below output.
Input:
var = ['ant','bat','cat','Bat','Lion','Goat','Cat','Ant']
Output:
['ant', 'Ant', 'bat', 'Bat', 'cat', 'Cat', 'Goat', 'Lion']
The
sort()
method and thesorted()
function take a key argument:The function named in
key
is called for each value and the return value is used when sorting, without affecting the actual values:To sort
Ant
beforeant
, you'd have to include a little more info in the key, so that otherwise equal values are sorted in a given order:The more complex key generates
('ANT', False)
forAnt
, and('ANT', True)
forant
;True
is sorted afterFalse
and so uppercased words are sorted before their lowercase equivalent.See the Python sorting HOWTO for more information.
New answer for Python 3, I'd like to add two points:
str.casefold
for case-insensitive comparisons.That is:
(which sorts in-place) and now:
Or, to return a new list, use
sorted
Why is this different from
str.lower
orstr.upper
? According to the documentation:I need to add yet another answer, since both the accepted answer and the newer versions lack one important thing:
The here proposed case-insensitive sorting is not stable in the ordering of "equal" keys!
That means: When you have a mixture of mixed case strings that you want to sort, you get a correctly sorted list, but it is undefined whether "AbC" comes before "aBc" or after. This may even vary between runs of the same program.
In order to always have the same output with a stable default ordering of strings, I use the following function:
This way, the original key is always appended as a fallback ordering when the casefold version does not supply a difference to sort on.