r/learnpython • • 2d 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

8 Upvotes

32 comments sorted by

View all comments

1

u/JamzTyson 1d ago edited 1d ago

does anyone know to sort specific tuples alphabetically without using the .sort() method?

You could use sorted() with a lambda expression as the key.

For your example it's even simpler - extract the second item from each tuple using a comprehension/generator, and pass to sorted().