Can you explain the second line with explain?
spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
print(spam)
Can you explain the second line with explain?
spam = ['a', 'z', 'A', 'Z']
spam.sort(key=str.lower)
print(spam)
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]
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']
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.
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.
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.
I had never programming in Python, but what i see: