[Python] Differences in list sorting in python, but not sure why?

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I expected below two codes should work identical. But they are not, as their outputs are different. Not sure, how list.sort(key) function works exactly in these cases. If anyone knows exactly how these list sorting with key attribute works, share your thought.

    #code-1:
    a = [1,3,4,5,1,7,9,9,9,9,9,1,3,2]
    x = a.copy()
    a.sort(key=x.count,reverse=True)
    print(a)

    #code-2:
    a = [1,3,4,5,1,7,9,9,9,9,9,1,3,2]
    a.sort(key=a.count,reverse=True)
    print(a)

    Continue reading...

Compartilhe esta Página