Reputation: 3
I'm a new learner of python/programming. Here is a question on top of head about the use of function in python.
If I had a list called myList.
myList.sort()
sorted(myList)
Note the difference between the use of two functions, one is to apply the function to myList
, the other one is use myList
as a parameter to the function.
My question is, each time when I use a function.
I have been confused with this for quite long time. appreciate any explanations.
Thanks.
Upvotes: 0
Views: 118
Reputation: 50076
Only sorted
is a function - list.sort
is a method of the list
type.
Functions such as sorted
are applicable to more than a specific type. For example, you can get a sorted list
, set
, or even a temporary generator. Only the output is concrete (you always get a new list
) but not the input.
Methods such as sort
are applicable only to the type that holds them. For example, there is a list.sort
method but not a dict.sort
method. Even for types whose methods have the same name, switching them is not sensible - for example, set.copy
cannot be used to copy a dict
.
An easy way to distinguish the two is that functions live in regular namespaces, such as modules. On the other hand, methods only live inside classes and their instances.
sorted # function
list.sort # method
import math
math.sqrt # function
math.pi.as_integer_ratio # method
Conventionally, Python usually uses functions for immutable actions and methods for mutating actions. For example, sorted
provides a new sorted list leaving the old one untouched; my_list.sort()
sorts the existing list, providing no new one.
my_list = [4, 2, 3, 1]
print(sorted(my_list)) # prints [1, 2, 3, 4]
print(my_list) # prints [4, 2, 3, 1] - unchanged by sorted
print(my_list.sort()) # prints None - no new list produced
print(my_list) # prints [1, 2, 3, 4] - changed by sort
Upvotes: 1
Reputation: 859
There are two big differences between list.sort and sorted(list)
The list.sort() sorts the list in-place, which means it modifies the list. The sorted function does not modify original list but returns a sorted list
The list.sort() only applies to list (it is a method), but sorted built-in function can take any iterable object.
Please go through this useful documentation.
Upvotes: 2
Reputation: 2980
sort()
is an in-place function whereas sorted()
will return a sorted list, but will not alter your variable in place. The following demonstrates the difference:
l = [1, 2, 1, 3, 2, 4]
l.sort()
print(l) --returns [1, 1, 2, 2, 3, 4]
l = [1, 2, 1, 3, 2, 4]
new_l = sorted(l)
print(new_l) -- returns [1, 1, 2, 2, 3, 4]
print(l) -- [1, 2, 1, 3, 2, 4]
If you want to maintain the original order of your list use sorted
, otherwise you can use sort()
.
Upvotes: 1