YouTip LogoYouTip

Python Func Sorted

# Python2.x Python sorted() Function [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description The **sorted()** function performs a sorting operation on all iterable objects. > **Difference between sort and sorted:** > > > `sort` is a method applied to a list, while `sorted` can perform sorting operations on all iterable objects. > > > The `list`'s `sort` method operates on the existing list in place and returns `None`, whereas the built-in `sorted` function returns a new list, rather than operating on the original. ## Syntax sorted syntax: sorted(iterable, cmp=None, key=None, reverse=False) Parameter explanation: * iterable -- An iterable object. * cmp -- A comparison function. This function takes two parameters, whose values are taken from the iterable object. This function must follow the rule: return 1 if greater, -1 if less, and 0 if equal. * key -- Primarily used for comparison. It takes a single parameter. The specific function's parameter is taken from the iterable object, specifying an element within the iterable object to sort by. * reverse -- Sorting rule. `reverse = True` for descending order, `reverse = False` for ascending order (default). ## Return Value Returns a new sorted list. ## Examples The following examples demonstrate the usage of `sorted`: >>>a = [5,7,6,3,4,1,2]>>>b = sorted(a)# Keep the original list>>>a[5, 7, 6, 3, 4, 1, 2]>>>b[1, 2, 3, 4, 5, 6, 7]>>>L=[('b',2),('a',1),('c',3),('d',4)]>>>sorted(L, cmp=lambda x,y:cmp(x,y))# Using cmp function[('a', 1), ('b', 2), ('c', 3), ('d', 4)]>>>sorted(L, key=lambda x:x)# Using key[('a', 1), ('b', 2), ('c', 3), ('d', 4)]>>>students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>>sorted(students, key=lambda s: s)# Sort by age[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>>sorted(students, key=lambda s: s, reverse=True)# Descending order[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>> [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Kotlin SetupPython Func Id β†’