0

I've been sorting list's values in ascending order and I found to cast the list into set and thereafter cast it back into list solves the problem for example

attempted = [2, 4, 1, 3, 5]
print(list(set(attempted))) # output [1, 2, 3, 4, 5]

and also is the same when list is made up by alphabets but when numbers are in the form of string(str) this does nothing, for example

lit = ['2','4', '1', '3', '5']
print(list(set(lit))) # output keeps changing by the time

but when sorted method is applied to the list it respects the ascending order like

lit = ['2','4', '1', '3', '5']
res = sorted(list(set(lit)))
print(res) # ['1', '2', '3', '4', '5']

and I don't understand why set can't sort the numbers which are in the form of string(str) by default without adding sorted method.

waiting for your good answers, suggestion and documentations about it

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
  • 3
    a `set` doesn't maintain order so converting it back to `list` will give you a random order. – Vishal Singh Jul 23 '20 at 11:12
  • 1
    @VishalSingh No, it wouldn't give the random order. – jizhihaoSAMA Jul 23 '20 at 11:13
  • it gives me random order when it is number in form of string only – Umutambyi Gad Jul 23 '20 at 11:14
  • 1
    a `set` is not sorted as others have mentioned, just because sometimes when you cast `set` on a sequence it maintains the order when printing the `set` does not guarantee that the same will be true over time. it states this fact in the first line of the official documentation --> https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset – gold_cy Jul 23 '20 at 11:18
  • 1
    Does this answer your question? [Converting a list to a set changes element order](https://stackoverflow.com/questions/9792664/converting-a-list-to-a-set-changes-element-order) – Vishal Singh Jul 23 '20 at 11:25
  • @VishalSingh I know that it change the order and I found that the order it respect is an ascending order at the most but I didn't understand that why it didn't respect it when is numbers in form of string – Umutambyi Gad Jul 23 '20 at 11:30
  • 2
    there is no documentation supporting that it maintains any order whether it's ascending for descending. – Vishal Singh Jul 23 '20 at 11:34

1 Answers1

0

set only removes the duplicates but doesn't care about the order.So after converting it to set convert it back to list to get the right order.

Irfan wani
  • 4,084
  • 2
  • 19
  • 34