Python Forum
Newbie lambda question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Newbie lambda question (/thread-6833.html)



Newbie lambda question - Truman - Dec-09-2017

I'm reading python tutorial and as an example of use of lambda there is this code:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
I do not understand this code, hope that somebody can explain me the logic behind the output:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


RE: Newbie lambda question - Windspar - Dec-09-2017

lambda are simple functions
code equal to
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
def pair_sort(pair):
	return pair[1] # this point to second object in list (1, 'one')[1] == 'one' 

pairs.sort(key=pair_sort)
print(pairs)



RE: Newbie lambda question - wavic - Dec-10-2017

lambda pair: pair[1]
lambda is called an anonymous function. The argument is passed before the ":". The expression which returns some value is after the colons. In this case, this is pair[1] which points to the second element of an iterable. So the list will be sorted by the second element of the tuples.


RE: Newbie lambda question - Truman - Dec-10-2017

(Dec-10-2017, 06:33 AM)wavic Wrote:
lambda pair: pair[1]
lambda is called an anonymous function. The argument is passed before the ":". The expression which returns some value is after the colons. In this case, this is pair[1] which points to the second element of an iterable. So the list will be sorted by the second element of the tuples.

The second element of the iterable is "(2, 'two')"? Unfortunately, I still don't understand this order 4-1-3-2.


RE: Newbie lambda question - hshivaraj - Dec-10-2017

(1, 'one')
(2, 'two')
(3, 'three')
(4, 'four')
The second element of all the tuple is

'one'
'two'
'three'
'four'
if you sort the above words, it would come out as

(4, 'four'), 
(1, 'one'), 
(3, 'three'), 
(2, 'two')



RE: Newbie lambda question - j.crater - Dec-10-2017

As wavic said, list is sorted by second element of the tuples. In your list (iterable) they are strings. Strings are ordered lexically, so "four" is first one, as "f" appears in alphabet before the rest of the initials of other values ("one", "two" and "three").


RE: Newbie lambda question - Truman - Dec-11-2017

(Dec-10-2017, 04:54 PM)j.crater Wrote: As wavic said, list is sorted by second element of the tuples. In your list (iterable) they are strings. Strings are ordered lexically, so "four" is first one, as "f" appears in alphabet before the rest of the initials of other values ("one", "two" and "three").

This is what completely missed. Wall
Thank you all.