Python TypeError: sort() takes no positional arguments

2024/10/5 19:15:59

I try to write a small class and want to sort the items based on the weight. The code is provided,

class Bird:def __init__(self, weight):# __weight for the private variableself.__weight = weightdef weight(self):return self.__weightdef __repr__(self):return "Bird, weight = " + str(self.__weight)if __name__ == '__main__':# Create a list of Bird objects.birds = []birds.append(Bird(10))birds.append(Bird(5))birds.append(Bird(200))# Sort the birds by their weights.birds.sort(lambda b: b.weight())# Display sorted birds.for b in birds:print(b)

When I run the program, I get the error stack of Python TypeError: sort() takes no positional arguments. Whats the issue here?

Answer

Exactly what it says: sort doesn't take any positional arguments. It takes a keyword-only argument named key:

birds.sort(key=lambda b: b.weight())

From the documentation:

sort(*, key=None, reverse=False)

This method sorts the list in place,using only < comparisons between items. Exceptions are not suppressed- if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

sort() accepts two arguments that can only be passed by keyword(keyword-only arguments):

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

[...]

The * in the signature is the separator between positional parameters and keyword-only parameters; its position as the initial "argument" indicates the lack of positional parameters.

https://en.xdnf.cn/q/70452.html

Related Q&A

Trouble with basemap subplots

I need to make a plot with n number of basemap subplots. But when I am doing this the all the values are plotted on the first subplot.My data is a set of n matrixes, stored in data_all.f, map = plt.sub…

Remove circular references in dicts, lists, tuples

I have this following really hack code which removes circular references from any kind of data structure built out of dict, tuple and list objects.import astdef remove_circular_refs(o):return ast.liter…

how to change image format when uploading image in django?

When a user uploads an image from the Django admin panel, I want to change the image format to .webp. I have overridden the save method of the model. Webp file is generated in the media/banner folder b…

Write info about nodes to a CSV file on the controller (the local)

I have written an Ansible playbook that returns some information from various sources. One of the variables I am saving during a task is the number of records in a certain MySQL database table. I can p…

Python minimize function: passing additional arguments to constraint dictionary

I dont know how to pass additional arguments through the minimize function to the constraint dictionary. I can successfully pass additional arguments to the objective function.Documentation on minimiz…

PyQt5 triggering a paintEvent() with keyPressEvent()

I am trying to learn PyQt vector painting. Currently I am stuck in trying to pass information to paintEvent() method which I guess, should call other methods:I am trying to paint different numbers to a…

A python regex that matches the regional indicator character class

I am using python 2.7.10 on a Mac. Flags in emoji are indicated by a pair of Regional Indicator Symbols. I would like to write a python regex to insert spaces between a string of emoji flags.For exampl…

Importing modules from a sibling directory for use with py.test

I am having problems importing anything into my testing files that I intend to run with py.test.I have a project structure as follows:/ProjectName | |-- /Title | |-- file1.py | |-- file2.py | …

Uploading and processing a csv file in django using ModelForm

I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code. This is my html form (upload_csv1.html):<form action="{% url myapp:upload_csv %}" me…

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

I am trying to get my head around matplotlibs state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should…