What does a list sort(key=str.lower) do?

Question:

Can you explain the second line with explain?

spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
print(spam)
Asked By: amrit shahi

||

Answers:

spam.sort(key=str.lower)

is sorting your spam list alphabetically as it’s case-insensitive. So if you change your 3rd line to

print(spam)

you get

['a', 'A', 'z', 'Z']

without the key in your sort the sorted list would be

['A', 'Z', 'a', 'z']
Answered By: po.pe

I had never programming in Python, but what i see:

  • spam is array of strings
  • spam.sort = sorts array, key – is current value, you can do smth.
  • str.lower – means you will translate each string to lower case (L => l)
  • and last line means you returns that array (maybe…)
Answered By: Ramazan Aliskhanov

spam is a list, and lists in python have a built-in sort function that changes the list order from low to high values.

e.g.

Nums = [2,1,3]
Nums.sort()
Nums

Output

[1,2,3]

The key parameter of sort is a function that is applied to each element of the list before comparison in the sorting algorithm. str.lower is a function that returns characters in lowercase.

e.g.

A -> a

So, the second line sorts spam by the lowercase values of its elements.

Which should result in

[a,A,z,Z]
Answered By: shaiel cohen

spam.sort(key=str.lower)

sort() is a default function for sorting in python and it can take some sorting function as a parameter.
here key = str.lower is the sorting function which means that it should parse every string to lower case before sorting.
which means that this is case in sensitive search.

Answered By: Usama Nawaz

It performs case insensitive sorting.

Let’s modify your example a bit, to include another entry “a”:

spam = ['a', 'z', 'A', 'Z','a']

Naturally, you’d expect first “a” and second “a” to occur together. But they don’t when you give key=str.lower, because of the properties of string ordering. Instead, a plain list.sort call will give you:

spam = ['a', 'z', 'A', 'Z','a']
spam.sort()
print(spam)

output
['A', 'Z', 'a', 'a', 'z']

On the other hand, specifying str.lower gives you this:

spam = ['a', 'z', 'A', 'Z','a']
spam.sort(key=str.lower)
print(spam)

output:
['a', 'A', 'a', 'z', 'Z']

Here, the original list elements are sorted with respect to their lowercased equivalents.

Answered By: Prathamesh

Basically, when str.lower is done then the data in spam becomes ‘a’,’z’,’a’,’z’ due to which when sorting is done then both ‘a’ will come first and then ‘z’ … but as the actual spam is not altered and only while sorting the data’s case was changed so you get the output as ‘a’ ‘A’ ‘z’ ‘Z’ ..
same result you will get when you do key=str.upper.

Answered By: Sandeep Kothari
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.