Python sort() function arguments

0 votes

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

Sep 12, 2018 in Python by ana1504.k
• 7,870 points
283 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 SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

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

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

answered Jul 29 in Python by Neel
• 3,010 points
14 views
0 votes
0 answers

Can we create a python function to sort a list?

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

Aug 7 in Python by Waseem
• 4,480 points
8 views
0 votes
1 answer

What is the use of raw_input function in Python?

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

answered May 2, 2018 in Python by aayushi
• 750 points
106 views
0 votes
1 answer

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

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

answered May 22, 2018 in Python by charlie_brown
• 7,720 points
56 views
+1 vote
2 answers

how can i count the items in a list?

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

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 277 views
0 votes
1 answer

Sort list by frequency in python

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

answered May 13 in Python by SDeb
• 13,160 points
63 views
0 votes
1 answer

Python: Sort list of lists numerically

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

answered May 20 in Python by SDeb
• 13,160 points
117 views