[Python] When making a set out of sorted list, the output set is not sorted [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    Could anyone please explain to me why making a set out of a sorted list results in a set which is NOT sorted?

    list.sort() should sort the list in place, as it does. set(list) should return unique values of the list, as it does.

    But why is the resulting set not sorted? Do I need to make a set, turn it back into list2 and then sort list2?

    (Using Python 2.7.6)

    Code:

    def longest(s1, s2):
    list = []
    s = s1 + s2
    for letter in s:
    list.append(letter)
    print list
    list.sort()
    print list
    unique = set(list)
    print unique
    s4 = ""
    for item in unique:
    s4 = s4 + item
    print s4
    return s4


    Console output:

    ['a', 'r', 'e', 't', 'h', 'e', 'y', 'h', 'e', 'r', 'e', 'y', 'e', 's', 't', 'h', 'e', 'y', 'a', 'r', 'e', 'h', 'e', 'r', 'e']
    ['a', 'a', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'h', 'h', 'h', 'h', 'r', 'r', 'r', 'r', 's', 't', 't', 'y', 'y', 'y']
    set(['a', 'e', 'h', 's', 'r', 't', 'y'])
    aehsrty

    Continue reading...

Compartilhe esta Página