0 votes

Can we have other arguments than key such as value for sort() function in Python ?

Sep 12, 2018 in Python 7,233 views

## 1 answer to this question.

0 votes

Both sort and sorted have three keyword arguments: cmp, key and reverse.

```L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list```

Using key and reverse is preferred, because they work much faster than an equivalent cmp.

key should be a function which takes an item and returns a value to compare and sort by. reverseallows to reverse sort order.

## Example

```>>> from operator import itemgetter

>>> a = range(5)
>>> b = a[::-1]
>>> c = map(lambda x: chr(((x+3)%5)+97), a)
>>> sequence = zip(a,b,c)

# sort by first item in a tuple
>>> sorted(sequence, key = itemgetter(0))
[(0, 4, 'd'), (1, 3, 'e'), (2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c')]

# sort by second item in a tuple
>>> sorted(sequence, key = itemgetter(1))
[(4, 0, 'c'), (3, 1, 'b'), (2, 2, 'a'), (1, 3, 'e'), (0, 4, 'd')]

# sort by third item in a tuple
>>> sorted(sequence, key = itemgetter(2))
[(2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c'), (0, 4, 'd'), (1, 3, 'e')]```
answered Oct 8, 2018 by
• 13,300 points

0 votes
1 answer

## What are the arguments of sorted() function in Python?

Sorted() sorts any sequence (list, tuple) and ...READ MORE

0 votes
0 answers

## Can we create a python function to sort a list?

I need the logic apart from the ...READ MORE

0 votes
1 answer

## What is the use of raw_input function in Python?

raw_input fuction is no longer available in ...READ MORE

0 votes
1 answer

## What does ' -> ' mean in Python function definitions?

It's a function annotation. In more detail, Python 2.x ...READ MORE

0 votes
1 answer

## how do i change string to a list?

suppose you have a string with a ...READ MORE

0 votes
2 answers

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote
2 answers

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

0 votes
1 answer

## how do i use the enumerate function inside a list?

Enumerate() method adds a counter to an ...READ MORE

0 votes
1 answer

## Sort list by frequency in python

You can try the following for a ...READ MORE

0 votes
1 answer

## Python: Sort list of lists numerically

You can try and De-dupe it with ...READ MORE