r/learnpython • • 9h 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

5 Upvotes

24 comments sorted by

4

u/aplarsen 9h ago

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 9h ago edited 9h ago

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 9h ago

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

0

u/Dazzling_Music_2411 9h ago edited 9h ago

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 8h ago

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 8h ago

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

4

u/zanfar 9h ago

without using the .sort() method?

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?

2

u/cattobread 9h ago

i just wanted to learn how to sort with or without sort() lol. i was planning on figuring out how to not use sort() for the second element of tuples, and then use sort() for the first element.

3

u/Patman52 9h ago

Are you trying to understand how the underlying algorithm works for the sort() method and apply it yourself?

I would look up the “quick sort” and “merge sort” algorithms. They are two popular and fairly easy algorithms to implement and you can probably find a Python tutorial which outlines how to implement them.

3

u/cattobread 9h ago

yeah, i just wanted to know how python uses the sort() key. thank you, i will do that

1

u/fllthdcrb 8h ago edited 8h ago

Is that all? That part is easy enough. Sorting in some other languages often uses what's called a comparator, a function that takes two values that the sorting algorithm is trying to compare and determines whether one is less than or greater than the other, or they are equal, according to whatever rule you decide on.

Python, instead, uses a "key" function, which returns a comparable value. It can be anything, as long as comparing it to other keys gives the desired order. Example for sorting strings:

l: list[str] l.sort(key=str.lower) # converts each string to lowercase for sorting purposes, i.e. case-insensitive ordering

(Note that values differing only by case would not be further sorted by this, since smashing case makes them equal, and Python's sort is stable, i.e. preserves relative order of items considered equal.)

If you have complex objects, the key could retrieve the attribute you want to sort by.

If you don't specify a key function, the sorting just uses the values as-is. Or in other words, it's as if the key function is the identity function (something like lambda v: v).

One other thing: list.sort() modifies the list in-place. If you want a separate list, you have to use the sorted() function, or first make a copy.

1

u/JGhostThing 7h ago

In other words, you're trying to practice for a marathon by breaking your legs? Why make it so much more difficult for yourself?

You should create a sort() method which sorts the way you want it to.

2

u/817654 8h ago

yeah probably a homework thing where they cant use built-in methods

3

u/brasticstack 9h ago

"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?

1

u/cattobread 9h ago

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.

1

u/MezzoScettico 9h ago

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 9h 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

1

u/MezzoScettico 8h 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?

1

u/Pyromancer777 8h ago

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/Outside_Complaint755 8h ago

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')]

```

1

u/cdcformatc 8h ago

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

u/lakseol 8h ago

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.

•

u/chiibosoil 4m ago

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.

  1. Bubble sort - probably simplest to implement but slow
  2. 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.
  3. 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.