Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why some methods we can apply to an object and define it in a variable, but for some we cant?

if we have a file, we can read the lines and store it in a variable. such as:

with open('test.py', 'r') as file:
    f = file.readlines()

however, for some methods we can’t add it to an object (sort it) and store in a variable:

cars = ['Ford', 'BMW', 'Volvo']
y = cars.sort()
print(y)

And we should do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)

Why?
Yeah, this might be a banal question, however, there’s no learning without banal questions.

>Solution :

sort modifies the list instance in-place, so it does not return anything. It is a convention for mutating methods to return nothing (i.e. None).

You can use y = sorted(cars) to create a sorted copy of the cars list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading