TypeError: sort() takes no positional arguments in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: sort() takes no positional arguments in Python #

The Python "TypeError: sort() takes no positional arguments" when we try to pass positional arguments to the sort() method. To solve the error, pass the key or reverse keyword arguments to the method or call it without passing any arguments.

typeerror sort takes no positional arguments

Here is an example of how the error occurs.

main.py
my_list = ['C', 'B', 'A', 'D'] # ⛔️ TypeError: sort() takes no positional arguments my_list.sort(lambda x: x.lower())

The list.sort method takes 2 optional keyword arguments - key and reverse.

We tried to pass the key argument as a positional argument which caused the error.

You can pass the argument as a keyword argument instead.

main.py
my_list = ['C', 'B', 'A', 'D'] my_list.sort(key=lambda x: x.lower()) print(my_list) # 👉️ ['A', 'B', 'C', 'D']

The other keyword argument the sort method takes is reverse.

main.py
my_list = ['C', 'B', 'A', 'D'] my_list.sort(key=lambda x: x.lower(), reverse=True) print(my_list) # 👉️ ['D', 'C', 'B', 'A']

Alternatively, you can call the sort method without providing any arguments.

main.py
my_list = ['C', 'B', 'A', 'D'] my_list.sort() print(my_list) # 👉️ ['A', 'B', 'C', 'D']

The list.sort method sorts the list in place and it uses only < comparisons between items.

The method takes the following 2 keyword-only arguments:

NameDescription
keya function that takes 1 argument and is used to extract a comparison key from each list element
reversea boolean value indicating whether each comparison should be reversed

Note that the list.sort method mutates the list in place and returns None.

You can use the sorted function if you need a new list instance rather than an in-place mutation.

The list.sort() method takes keyword-only arguments, so if we try to pass positional arguments to the method, the error is caused.

Conclusion #

The Python "TypeError: sort() takes no positional arguments" when we try to pass positional arguments to the sort() method. To solve the error, pass the key or reverse keyword arguments to the method or call it without passing any arguments.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.