[Python] Why does sort() with key function not do anything while sorted() is working?

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list of integers with duplicates and I need to sort it by the number of these duplicates.

    For example:

    input: n = [2, 4, 1, 2]
    output: n = [4, 1, 2, 2]


    I wrote some code and noticed, that sort() does not change the list. But if I try to use sorted() with the same key argument, then it works just fine. What is the reason behind this?

    My code:

    nums = [2, 4, 1, 2]
    nums.sort(key = lambda x: nums.count(x))
    print(nums)


    Can it be connected to sort() method using in-place algorithm?

    Continue reading...

Compartilhe esta Página