user3728945
user3728945

Reputation:

how is this program working [python 3.x]?

I am learning python 3.x and got stuck on this program. Can someone please explain me whats happening in this program?

input:-

   pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
   pairs.sort(key=lambda pair: pair[1])

output:-

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

Upvotes: 1

Views: 162

Answers (2)

ryanpattison
ryanpattison

Reputation: 6251

key=lambda pair: pair[1] is used to compare elements in the list during sorting. Since the lambda indexes a pair to its second value, it will compare the strings 'one', 'two', etc during sorting.

Strings are compared by their lexicographical order which is similar to alphabetical order, but also defines orderings for non alphabet characters too (like punctuation and digits). Sorting by the strings results in the pair with 'four' being first since it starts with 'f' and 'one' being second since it starts with 'o' and 'f' < 'o' etc.

Upvotes: 1

nonamer92
nonamer92

Reputation: 1917

You are sorting the pairs by the second variable ([1]) which are : 'one','two','three','four' therefore they will be sorted by their alphabetical value.

Upvotes: 0

Related Questions