chevron_left
Cookbooks
Accessing an item in a listAdding items to a listChecking if a list is emptyChecking whether a value is in a listConcatenating two listsCopying a list in PythonDifference between append and extend methodsDifference between sort and sortedFinding the index of an element in a listFinding the length of a listIterating from index oneLooping through listsModifying listsPrinting a list in reverse orderRemoving items from a listSorting a listUsing enumerate and zip at the same time
0
0
0
new
Difference between sort and sorted in Python
Programming
chevron_rightPython
chevron_rightOperations
chevron_rightList Operations
chevron_rightCookbooks
schedule Jul 1, 2022
Last updated Python
Tags tocTable of Contents
expand_more The difference between sort and sorted in Python is that while list.sort(~)
permanently modifies the order of the original list, sorted(~)
returns your list in a sorted order but does not actually modify the original list.
sort method
To permanently modify order of elements in animals
according to reverse alphabetical order:
animals = ['cat', 'doge', 'bird']print("Using sort: ", animals.sort(reverse=True))print("Original list: ", animals)
Using sort: NoneOriginal list: ['doge', 'cat', 'bird']
Notice that nothing is returned from animals.sort(reverse=True)
. However, the order of elements in the original list is modified.
sorted method
To return the list animals
in reverse alphabetical order:
animals = ['cat', 'doge', 'bird']print("Using sorted: ", sorted(animals, reverse=True))print("Original list: ", animals)
Using sorted: ['doge', 'cat', 'bird']Original list: ['cat', 'doge', 'bird']
Notice that sorted(animals, reverse=True)
returns the sorted list. However, the original list is unmodified.
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...
0
0
0
Enjoy our search