# Sorted() function in Python

## Sorted() function in Python :

Sorted()  is an in-built function in python , which used to sort any type of sequence like list , tuple.

Set is already sorted we need not to sort  a set. Sorted sort any type of sequence  and returns the sequence in sorted manner without changing the original sequence. ## sorted() in Python

The sorted() function is a way to sort a list without using sort() function.

Example :

•   ( 2 , 1, 4 ,3)
• sorted = ( 1 , 2 , 3 , 4)

### Syntax :

`  sorted( iterable , key , reverse )   Parameters : sorted takes three parameters from which two are optional.  Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.  Key(optional) : A function that would server as a key or a basis of sort comparison.  Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.`

#### Code 1 :

Run
```#Sorted
li=[(1,2),(4,5) ,( 3 ,9)]
print('sorted list:',sorted(li))
print(' Orginal List :' ,li)```

### Output :

`sorted list: [(1, 2), (3, 9), (4, 5)]Orginal List : [(1, 2), (4, 5), (3, 9)]`

#### User Defined Sorting :

• sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value.

#### Code 2:

Run
```#Sorted
L = [[1,2,5], [3,6], [2,1,9], [8,0,0]]
print ("Normal sort :", sorted(L))
print ("Sort with sum :", sorted(L, key = sum))```

### Output :

`Normal sort : [[1, 2, 5], [2, 1, 9], [3, 6], [8, 0, 0]]Sort with sum : [[1, 2, 5], [8, 0, 0], [3, 6], [2, 1, 9]]`

In the above Program , the inner list is sorted according to their sum in ascending order as sum of ( 1+ 2 + 3) < ( 3+6) .

Which means that the slists would be sorted based on their sum instead

### Code 3:

Run
```#Sorted
# List elements: (Student's Name, Marks out of 100 , Age)
p_list = [
('A', 70, 18),
('B', 85, 22),
('D', 45, 30),
('C', 99, 22),
('E', 33, 42)
]
def sorting(item):
# Since highest marks first, least error = most marks
error = 100 - item
age = item
return (error, age)
sorted_list = sorted(p_list, key=sorting)
print(sorted_list)```

### Output :

`[('C', 99, 22), ('B', 85, 22), ('A', 70, 18), ('D', 45, 30), ('E', 33, 42)]`

P_list is sorted in such a way that the person with higher marks gets the first position in the list.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others