-2
mylist=['P','y','t','h','o','n']
print(set(mylist))

Convert list to set, but the set that I got does not follow the order like the list does

{'h', 'y', 'o', 't', 'P', 'n'}
Phong Diep
  • 35
  • 4

1 Answers1

2

You can't since sets do not have order.

You can, however, convert the set back to a sorted list, using the original list's indexes as the sorting key:

mylist = ['P', 'y', 't', 'h', 'o', 'n']
print(sorted(set(mylist), key=mylist.index))

outputs

['P', 'y', 't', 'h', 'o', 'n']

This obviously makes more sense if the original list contains duplicated items:

mylist = ['P', 'y', 't', 'h', 'h', 'h', 'o', 'n']
print(sorted(set(mylist), key=mylist.index))

also outputs

['P', 'y', 't', 'h', 'o', 'n']

A small caveat arises if the original list contains duplicated elements in non-consecutive indexes, due to the fact that list.index returns the index of the first occurrence that it finds.

mylist = ['c', 'b', 'c', 'a', 'b', 'a']
print(sorted(set(mylist), key=mylist.index))

outputs

['c', 'b', 'a']
DeepSpace
  • 78,697
  • 11
  • 109
  • 154