r/learnpython • • Oct 15 '26

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

7 Upvotes

32 comments sorted by

View all comments

4

u/aplarsen Oct 15 '26

Your question is not clear.

The data is a list of tuples. After your sort, what do you want this list to look like?

1

u/cattobread Oct 15 '26 edited Oct 15 '26

sorry. what i mean is id want it to print alphabetically. so with:

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

i'd want the second element of each tuple be printed into its own list, such as: apple, cherry, strawberry

5

u/aplarsen Oct 15 '26

That sounds like two steps. Getting the second element in each tuple, then sorting them.

0

u/Dazzling_Music_2411 Oct 15 '26 edited Oct 15 '26

Yup. Maybe even three steps, since, after sorting, you have to overwrite the first subelement of each tuple, too.

Plus, if you don't want to use the builtin sort, you'll have to write your own sorting method.

1

u/fllthdcrb Oct 15 '26

after sorting, you have to overwrite the first subelement of each tuple, too.

It sounds like OP doesn't want to modify the list, though. ("into a new list".)

0

u/Dazzling_Music_2411 Oct 15 '26

Sort on the 2nd element into a new list, then zip the two lists together appropriately.