Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I’m reading python3 official document and encounter a syntax pair[1] which I can’t understand.
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
# [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
pairs
is a list of tuples. (1, 'one')
is an example of a tuple with two elements.
From the docs:
Tuples are immutable sequences, typically used to store collections of heterogeneous data
We then sort that list in-place on the 2nd element of the tuple via key=lambda pair: pair[1]
(pair[1]
signifies that the sorting key should be the 2nd element of the tuple)
Since the second element is a string, the sort is done lexicopgraphically, or alphabetically.
From the docs:
list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
In [7]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
In [8]: pairs.sort(key=lambda pair: pair[1])
In [9]: pairs
Out[9]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
If you sort on the first element of the tuple, the sort is done on the integers and is done numerically
In [10]: pairs.sort(key=lambda pair: pair[0])
In [11]: pairs
Out[11]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
This questions here goes in more details about what a tuple is and
this question here goes in more details about how key
works in sorting functions sort()
and sorted()
–
In this case, you are passing a new "key" function into list.sort.
the key function will be given each item in the input list and should return the key to sort that item by. The lambda is defining
a function which takes one of those items (named pair inside the function),
and returns the second item (index 1) of it. list.sort then sort the items
in the original list based on this key, whereby you get "four", "one",
"three", "two" sorted as strings, but the output will include the full
pairs.
that is
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.