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,910 points
8,061 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,300 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, 2019 in Python by Neel
• 3,020 points
1,161 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, 2019 in Python by Waseem
• 4,540 points
487 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
1,279 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 23, 2018 in Python by charlie_brown
• 7,720 points
920 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,454 views
0 votes
1 answer
0 votes
1 answer

Sort list by frequency in python

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

answered May 13, 2019 in Python by SDeb
• 13,300 points
6,298 views
0 votes
1 answer

Python: Sort list of lists numerically

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

answered May 20, 2019 in Python by SDeb
• 13,300 points
2,274 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP