Name | sorted() |
||||
---|---|---|---|---|---|
Examples |
numbers = [3.4, 3.6, 2, 0, 7.1] sorted_numbers = sorted(numbers) print(sorted_numbers) # Prints [0, 2, 3.4, 3.6, 7.1] # original list left unchanged print(numbers) # Prints [3.4, 3.6, 2, 0, 7.1] animals = ["deer", "elephant", "bear", "aardvark", "cat"] sorted_animals = sorted(animals) print(sorted_animals) # Prints ['aardvark', 'bear', 'cat', 'deer', 'elephant'] # reverse=True reverses the order of the sort rev_animals = sorted(animals, reverse=True) print(rev_animals) # Prints ['elephant', 'deer', 'cat', 'bear', 'aardvark'] # sorted() lets you sort any iterable, not just lists! word = "parabolas" sorted_word = sorted(word) print(sorted_word) # Prints ['a', 'a', 'a', 'b', 'l', 'o', 'p', 'r', 's'] # sorted() is, by default, case insensitive items = ["Abacus", "abacus", "Zwieback", "zwieback"] sorted_items = sorted(items) print(sorted_items) # Prints ['Abacus', 'Zwieback', 'abacus', 'zwieback'] # Pass your own function as an argument to sort() to apply a transformation to # items before sorting def case_insensitive(item): return item.lower() sorted_items = sorted(items, key=case_insensitive) print(sorted_items) # Prints ['Abacus', 'abacus', 'Zwieback', 'zwieback'] # sort list of strings by their length, using the built-in function len() # as the key parameter items = ["buffalo", "charcoal", "desk", "egg", "flask"] sorted_items = sorted(items, key=len) print(sorted_items) # Prints ['egg', 'desk', 'flask', 'buffalo', 'charcoal'] # You can use the "key" parameter and the "reverse" parameter in the same # call to sort! sorted_items = sorted(items, key=len, reverse=True) print(sorted_items) # Prints ['charcoal', 'buffalo', 'flask', 'desk', 'egg'] | ||||
Description |
Returns a sorted copy of the given list (or other iterable). Like the
sort() method of the list object, it can take an optional key
parameter to specify a function that should be evaluated for each item in the
list before sorting that item. The optional parameter reverse, if set
to True, causes sorted() to perform its sorting operation in
reverse order. The sorted() function differs from a list object's sort() method in two important ways. First, it returns a copy of the sorted list, leaving the original list intact (instead of sorting the list in-place). Second, sorted() works with any iterable (e.g., strings, tuples, dictionaries), not just lists. For more information and examples, consult the Sorting Mini-HOWTO on the Python Wiki. |
||||
Syntax | sorted(iterable) sorted(iterable, reverse=True) sorted(iterable, key=fn) | ||||
Parameters |
| ||||
Related |
.reverse() |
Updated on Mon Sep 21 15:53:25 2020.
If you see any errors or have comments, please let us know.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License