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.
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.
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.
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.