sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).
sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.
Use
list.sort()when you want to mutate the list,sorted()when you want a new sorted object back. Usesorted()when you want to sort something that is an iterable, not a list yet.For lists,
list.sort()is faster thansorted()because it doesn't have to create a copy. For any other iterable, you have no choice.No, you cannot retrieve the original positions. Once you called
list.sort()the original order is gone.
Code: https://www.30secondsofcode.org/articles/s/python-sortedlist-vs-list-sort
So I get that one of the main differences between sorted() and sort() is that sorted() returns a new list and sort() modifies the list directly. But I don't understand why their outputs can't be exactly equal if they print out to being, in fact, exactly equal. For example:
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(f"Sorted list: {sorted_numbers}")
numbers.sort()
print(f"Sorted list: {numbers}")
print(numbers.sort() == sorted(numbers))This is the output:
Sorted list: [1, 1, 2, 3, 4, 5, 9] Sorted list: [1, 1, 2, 3, 4, 5, 9] False
As we can see, both sorted(numbers) and numbers.sort return what appears to be identical output: [1, 1, 2, 3, 4, 5, 9]. Of course, sort() has modified the original list, so that object has been changed by the end of the program. But if these two outputted lists are clearly identical from a mathematical perspective (ie: [1, 1, 2, 3, 4, 5, 9] == [1, 1, 2, 3, 4, 5, 9] is true on it's on terms as a standalone expression ) - then why won't Python embrace this apparently same understanding with: print(numbers.sort() == sorted(numbers))?
Is there some unseen object that represents the original list that is lingering unprinted in the background and attached to sorted(numbers)?
Thanks ahead of time for your interest and time on this matters.
Videos
Hello all,
I am working through the Python Crash Course book and I am currently in Chapter 3 and working with lists.
I am working on some of the practice problems that require using sort() and sorted(). In one of my practice problems, it required the use of sort() to permanently sort a list in alphabetical order and also temp sort a list. I understand that sort() will alter the actual contents of the list and assume re-write how it is stored in the variable, whereas I assume sorted() is creating some type of temp variable to store the sorted list.
I am confused between how they are used in code, I was using list.sort() with no problem, but I attempted to use list.sorted() and ran into an error. I was able to correct it by changing the syntax to sorted(list). Why does sort not work in the same fashion as .sort() does?
I looked back in the chapter and saw that it refers to sort() as a method and sorted() as a function, I tried to research and learn the difference between a method and function in python and got myself even more confused. Is there an easy explanation as to why sorted(list) works but list.sorted() does not?
Python sort() and sorted() are used to sort the data in ascending or descending order. Their goals are the same but are used in different conditions.
The Python sort() function is connected to the Python list and by default, sorts the list's contents in ascending order.
list.sort(reverse=False, key=None)
Python sorted() function is used to sort the iterable data. By default, this function sorts the data in ascending order.
sorted(iterable, key=None, reverse=False)
Here's a complete guide comparing both functions and pointing out differences👇👇
Python sort vs sorted - Detailed Comparison With Code
sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).
sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.
Use
list.sort()when you want to mutate the list,sorted()when you want a new sorted object back. Usesorted()when you want to sort something that is an iterable, not a list yet.For lists,
list.sort()is faster thansorted()because it doesn't have to create a copy. For any other iterable, you have no choice.No, you cannot retrieve the original positions. Once you called
list.sort()the original order is gone.
What is the difference between
sorted(list)vslist.sort()?
list.sortmutates the list in-place & returnsNonesortedtakes any iterable & returns a new list, sorted.
sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:
def sorted(iterable, key=None):
new_list = list(iterable) # make a new list
new_list.sort(key=key) # sort it
return new_list # return it
When is one preferred over the other?
- Use
list.sortwhen you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.) - Use
sortedwhen you want to retain the original sort order or when you wish to create a new list that only your local code owns.
Can a list be reverted to the unsorted state after list.sort() has been performed?
No - unless you made a copy yourself, that information is lost because the sort is done in-place.
Which is more efficient? By how much?
To illustrate the penalty of creating a new list, use the timeit module, here's our setup:
import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)] # list of lists
for l in lists:
random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""
And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:
Python 2.7
>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]
Python 3
>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]
After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.
import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""
I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%
>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]
I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.
Poke ran his own code as well, here's the code:
setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
print(t)
print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))
He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:
10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655
Conclusion:
A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.
Hey guys, just wondering if sorted() is always the superior method of sorting in python. In the spirit of learning, I've copying some C++ exercises in Python, and only stumbled on sorted() after recreating some others. Thanks for your help!
After this code, why would x and y be different? x seems in the wrong order.
from string import lower
x='the rain in Spain stays mainly in the plain because Spain gets all the rain'.split()
y=sorted(x,key=lambda el:(x.count(el),lower(el)))
x.sort(key=lambda el:(x.count(el),lower(el)))