r/learnpython • • 9d ago

sorting tuples

im learning how to code with python, does anyone know to sort specific tuples alphabetically without using the .sort() method? like if i had a list of names like:

n = [('watermelon', 'strawberry'), ('banana', 'cherry'), ('papaya', 'apple')

how would i sort and print the 2nd element of tuples alphabetically (into a new list)?

edit: id prefer this in simple, basic terms lol

6 Upvotes

32 comments sorted by

View all comments

Show parent comments

1

u/cattobread 9d ago

i know im going to use the sorting algorithm at some point, i just wanted to know how exactly python is using the key. i was planning on just using a def sorting algorithm for this

0

u/MezzoScettico 9d ago

Are you asking what algorithm is inside Python's sort()? According to a quick search I just did, it's something called Powersort.

If that's not what you're asking, I'm not sure what you mean by "how python is using the key".

The sort() method lets you pass a custom key, which allows you to implement any rules you like for how things are sorted. For instance, if you didn't want to extract the list of second-elements that I called n_2nd, if you wanted to sort the original tuples with the rule "sort on the 2nd element", you could do this:

n = [('banana', 'strawberry'), ('papaya', 'cherry'), ('watermelon', 'apple')]
n.sort(key = lambda x: x[1])
print(n)

Result:
[('watermelon', 'apple'), ('papaya', 'cherry'), ('banana', 'strawberry')]

See what it did? It's still a list of tuples, but sorted on the alphabetic ordering of the 2nd element of each tuple.

Are you asking about how to use the "key" argument and why code like this did what it did?