Reputation: 11
I was trying to grasp my head around the difference between .sort()
and sorted()
and their reverse in python but I don't seem to get any. Any help?
Upvotes: 1
Views: 1073
Reputation:
The difference between sort
and sorted
is that sorted(list)
returns a copy of the list without changing it, while list.sort()
changes the list.
Therefore, sorted
is a static method, while sort
is a list instance method.
Upvotes: 0
Reputation: 11
.sort() is a list method whereas sorted() is a built-in function but they effectively do the same thing. For example...
my_list = [2,6,5,1,3]
my_list.sort()
print(my_list)
>>>[1, 2, 3, 5, 6]
The sort() method changes the my_list variable. You can add a reverse = True
parameter into the parenthesis to reverse the list...
my_list = [2,6,5,1,3]
my_list.sort(reverse = True)
print(my_list)
>>>[6, 5, 3, 2, 1]
The sorted() function is different as it cannot chnage the my_list variable. eg...
my_list = [2,6,5,1,3]
sorted(my_list)
print(my_list)
>>>[2, 6, 5, 1, 3]
Instead you can assign the sorted(my_list) to a new variable...
my_list = [2,6,5,1,3]
new_list = sorted(my_list)
print(new_list)
>>>[1, 2, 3, 5, 6]
And if you want to reverse this list you can add reverse = True
into the parenthesis...
my_list = [2,6,5,1,3]
variable = sorted(my_list, reverse = True)
print(variable)
>>>[6, 5, 3, 2, 1]
Upvotes: 1
Reputation: 174
I think .sort() is a list method which sorts the list and sorted is a builtin function which accpets some iterable object and returns its sorted copy
Upvotes: 0
Reputation: 12523
The difference is that sorted(l) returns a copy of l without changing it, while l.sort() changes l. See the example below:
l = [3, 2, 4, 5, 1, 7]
l.sort()
==> returns None, but changes l
print(l) # As you can see, l is now sorted.
==> [1, 2, 3, 4, 5, 7]
# Create an unsorted list, again
l = [3, 2, 4, 5, 1, 7]
print(sorted(l))
==> [1, 2, 3, 4, 5, 7] # sorted(l) returns a sorted list
print(l) # but l itself didn't change.
==> [3, 2, 4, 5, 1, 7]
Upvotes: 3