Python TypeError: sort() takes no positional arguments

Python TypeError: sort() takes no positional arguments

Python sort() function takes no positional arguments.

For example, consider the following program, where we passed a function as argument to sort() method.

my_list = ['cherry', 'apple', 'mango', 'banana']
my_list.sort(str.lower)
print(my_list)
Run Code Copy

When you run this program, we get the following error in output.

Traceback (most recent call last):
  File "/Users/pythonexamplesorg/main.py", line 2, in <module>
    my_list.sort(str.lower)
TypeError: sort() takes no positional arguments

Please observe the definition of Python List sort() method, which is given below.

def sort(
    *,
    key: None = None,
    reverse: bool = False
) -> None: ...

It takes only two named arguments. One is key, and the other is reverse.

So, if you like to specify a key function to the List sort() method, you do that as shown in the following.

my_list = ['cherry', 'apple', 'mango', 'banana']
my_list.sort(key=str.lower)
print(my_list)
Run Code Copy

Or, if you would like to sort the list in descending order, you specify the reverse parameter using reverse named argument, as shown in the following.

my_list = ['cherry', 'apple', 'mango', 'banana']
my_list.sort(reverse=True)
print(my_list)
Run Code Copy

You can specify both the named arguments as shown, if required.

my_list = ['cherry', 'apple', 'mango', 'banana']
my_list.sort(key=str.lower, reverse=True)
print(my_list)
Run Code Copy

Summary

In this tutorial, we learned how to solve the exception: “TypeError: sort() takes no positional arguments” in Python.

Related Tutorials

Code copied to clipboard successfully 👍