r/learnpython • u/cattobread • 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
5
u/brasticstack Oct 15 '26
"does anyone know to sort specific tuples alphabetically without using the .sort() method?"
Sounds like homework to me, why would you avoid the built-in function that specifically does what you're trying to do?
0
u/cattobread Oct 15 '26
what i was doing was sorting the 2nd element in the subset without sort(), and then sorting the 1st element of the subset with the sort(). i just wanted to learn how to figure something out before using a shortcut to it, as a beginner.
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.
3
u/chiibosoil Oct 15 '26
Don't know why you need to do it, but you can't sort tuples itself as they are immutable.
What you need to do in general is to convert to list then sort then convert it back to tuple.
Search for different sort algorithms and apply that in your code.
Bubble sort - probably simplest to implement but slow
Quick sort, Merge sort, Heap sort - These share similar avg time complexities, but uses different logic and has other characteristics that differ significantly. Do a google search and you will find plenty of examples. In real-life scenario Quick sort is one of the fastest, due to it operating in-place and having excellent cache locality.
If sorting on specific data types like non-negative integers or fixed-length string. Check out non-comparison algorithm for sorting. Ex: Radix Sort, Counting Sort. These will be much faster in specific scenario.
2
u/RngdZed Oct 15 '26
Lambda or list comprehension would be my go-to, if, for some reason I'd want to make my life harder by avoiding the built-in, easy to use, sort() function
😋
Edit: if you're interested check on how to implement various sort algorithms in python, like bubble sort or that kind of stuff
1
u/Pyromancer777 Oct 15 '26
One thing to note: tuples are immutable, meaning once you write them you cannot make changes to their elements.
That being said, you have a list of tuples and lists can be sorted however you want. You can also write the values of the tuples into other data structures in whatever order that you want, but that's not necessarily sorting the tuples, but creating sorted lists from the values in the tuples.
For your case, you want to first identify how to index each element. Index references start outside and work their way inward. Once you can point to a specific element in your structure you then need to think of a way to do something to that value to get to your end-goal.
Since you said you wanted to sort the 2nd elements, the tuple references will be index 1 for all tuples in your list. Then you have to decide whether you want your output to be sorted in-place or if you want to create a new variable to hold your final and intermediary results. Not gonna give away an answer since other comments gave working examples, but I'm providing a way of breaking down the problem into parts, to hint at what you can do with those parts.
1
u/cdcformatc Oct 15 '26
there's like a million sorting algorithms, pick one of them and implement it on a list of strings. i like merge sort.
then just convert your list of tuples into a list of strings by getting the second element of each of them, then sort that list.
1
1
u/JamzTyson Oct 15 '26 edited Oct 15 '26
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().
1
u/WorriedTumbleweed289 Oct 15 '26 edited Oct 15 '26
Use sort with a function key that will return the second element of a tuple. Key is one of the arguments to sort.
Without using the sort() method, you can write your own. Google sorting algorithms. I don't think you want to do this unless it is a class assignment.
1
0
u/MezzoScettico Oct 15 '26
You want an output list that consists of the 2nd elements, in alphabetical order?
n = [('banana', 'strawberry'), ('papaya', 'cherry'), ('watermelon', 'apple')]
n_2nd = [pair[1] for pair in n]
n_2nd.sort()
print(n_2nd)
Output:
['apple', 'cherry', 'strawberry']Or, more compactly but also a little obscure,
n = [('banana', 'strawberry'), ('papaya', 'cherry'), ('watermelon', 'apple')]
print( sorted([pair[1] for pair in n]) )
Result:
['apple', 'cherry', 'strawberry']Is that what you want?
But you said you want to sort without using the sort method. Why? Since you want to sort something, you will need to apply a sorting algorithm at some point. You could look up sorting algorithms and write your own. You could build a class that implements a sorted data structure, so every time you add something to it, it is in your desired order. So you're still building your own sorting algorithm in effect.
Why don't you want to use sort()?
1
u/cattobread Oct 15 '26
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 Oct 15 '26
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?
0
u/Outside_Complaint755 Oct 15 '26
Instead of the sort method, you can use the sorted built in function which returns a new list
n = [('watermelon', 'strawberry'), ('banana', 'cherry'), ('papaya', 'apple')]
for tup in sorted(n, key=lambda x: x[1]):
print(tup[1])
If you're trying to make your own function to do the sorting, you would just need to compare the target element between two tuples and then swap their order in the list if needed.
For an example bubble sort:
def bubble_sort_by_second_element(seq):
made_swap = True
while made_swap:
made_swap = False
for i in range(len(seq) - 1):
if seq[i][1] > seq[i+1][1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
made_swap = True
n = [('watermelon', 'strawberry'), ('banana', 'cherry'), ('papaya', 'apple')]
print(f"Before sort: {n}")
bubble_sort_by_second_element(n)
print(f"After sort: {n}")
# Before sort: [('watermelon', 'strawberry'), ('banana', 'cherry'), ('papaya', 'apple')]
# After sort: [('papaya', 'apple'), ('banana', 'cherry'), ('watermelon', 'strawberry')]
0
u/lakseol Oct 15 '26
You said "i just wanted to learn how to sort" without using sort(). That means writing your own sort function. That's a really good exercise but not something you would do in practice. In that spirit the code below shows a very simple and very inefficient implementation of the quicksort algirithm:
def qsort(data):
"""Return a sorted list of values from sequence "data"."""
if not data:
return data
(*rest, pivot) = data
lesseq = [x for x in rest if x <= pivot]
greater = [x for x in rest if x > pivot]
return qsort(lesseq) + [pivot] + qsort(greater)That doesn't sort in-place but returns a new list.
The other part of your problem is that you apparently (it isn't clear) want to extract and sort on the second element of each tuple. Just create a new list containing only the second elements and then sort that.
1
u/RngdZed Oct 15 '26
But why give the dude the full answer.. you could pseudo code it for him at least. How does that help him learn how to do it himself..
0
u/lakseol Oct 15 '26
It's not the full answer. Since the question was unclear how can it be the full answer? It doesn't show any handling of key functions which might have been what the OP was asking about. If the OP tried to use it as an answer in some sort of problem question s/he would have to change it or do extra work to handle isolating the second element of each tuple.
But thanks for your input.
5
u/zanfar Oct 15 '26
Why? What does this get you, or what doesn't
sort()get you?Because I'm pretty sure about the answer to #1, have you read the
sort()documentation?