Does Python sort arrays with multiple keys with or without executing the second key? (It does execute the second key) If so is there a way to stop it from evaluating the second key when it is unnecessary? Is there a module that would be able to do this easily without having to add extra code?

import random
import itertools
alist=[random.randint(0,10000000) for i in range(10000)]
def cheap(x):
    return x%100000
def expensive(x):
    def primes():
        D = {}
        yield 2
        for q in itertools.count(3, 2):
            p = D.pop(q, None)
            if p is None:
                yield q
                D[q*q] = q
                x = p + q
                while x in D or x % 2 == 0:
                    x += p
                D[x] = p
    def nth_prime(n):
        if n < 1:
            raise ValueError("n must be >= 1 for nth_prime")
        for i, p in enumerate(primes(), 1):
            if i == n:
                return p
    return nth_prime(x%99999+1)

alist.sort(key=lambda x: (cheap(x),expensive(x)))
🔴 No definitive solution yet
📌 Solution 1

It does run the second function, one way around this is to sort it by the first key, and then the second

values = set(map(lambda x:x[1], alist)) newlist = [[y[0] for y in alist if y[1]==x] for x in values]

uhh, IDK past this point. I really just wanted to open a discussion,