Python Forum

Full Version: Newbie lambda question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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')]
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)
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.
(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.
(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')
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").
(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.