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

Question:

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:

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

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

Asked By: Hardliner

||

Answers:

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.

Answered By: Unmitigated
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.