1
ar=[10,20,20,10,10,30,50,10,20]  
ar.sort()  
nar = list(set(ar))

the result gives me

nar = [10,20,50,30] instead of [10,20,30,50]

could someone explain this

  • Does this help? https://stackoverflow.com/questions/9792664/converting-a-list-to-a-set-changes-element-order/41379007 – jdaz Jun 05 '20 at 05:26
  • Sets are unordered, no gaurantees therefore that the data will come out in order. You will need to run .sort on nar. – Hoppo Jun 05 '20 at 07:18

1 Answers1

0

Quick Summary

Sets do not preserve order by definition.

Still want to remove duplicates but also preserve order?

>>> from collections import OrderedDict
>>> items = [10, 4, 10, 2, 2, 2, 7]
>>> list(OrderedDict.fromkeys(items))
[10, 4, 2, 7]

I really hope this helps!

Thomas
  • 859
  • 6
  • 16