Reputation: 1490
I am getting the following error on console
newList = sorted(l,key=sort)
NameError: name 'sort' is not defined
after executing the following piece of code:
if __name__ == '__main__':
l= [[input(), float(input())] for _ in range(int(input()))]
print( l)
new = sorted(l,key=sort)
print(new)
From the given article I learned that key
parameter in sorted()
can use user/inbuilt Python methods. I am trying to sort my list alphabetically so I passed key=sort
with an understanding that it will sort my list alphabetically.
Please help me out where am I going wrong here.
Upvotes: 2
Views: 17976
Reputation: 2546
sorted()
function has an optional parameter called key
which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value.
Example:
If there is a list of tuples,
li = [('p1', 20), ('p2', 10), ('p3', 30)]
and you want to sort the elements of the list in such a way that the resulting order is as follows:
Ouptut: li = [('p2', 10), ('p1', 20), ('p3', 30)]
Then, all you need to do is, sort the tuples, based on the 2nd element in each tuple.
To do so, we need to use a custom method, which will be applied to each element and the elements will be sorted based on the representative of each element(i.e KEY).
Hence, the syntax to the same will be as follows:
sorted(li, key=lambda x: x[1])
Edit:
Sort is in itself a function, which is used to arrange elements in a specific order. But, it cannot be used to extract a representative (i.e a KEY) for each element in the list.
Upvotes: 5
Reputation: 27323
Well, sort
is not a user/built-in Python function. It is a method on lists, but, not a name accessible globally. Even if you would use it (through key=list.sort
), it would not give you your desired result, as the key function is used to transform each element before sorting.
By default (without specifying the key
parameter), sorted
should already sort strings alphabetically (sort of), same with lists containing lists with a string as the first item. If you want to sort "A"
and "a"
together (as well as "Z"
and "z"
), you could use the key function str.lower
, but you would need to apply that only to the first element of your inner lists:
new = sorted(l, key=lambda x: x[0].lower())
Upvotes: 2