0
a = [0, 22, 2, 3, 44, 5, 6, 27, 8, 19]
print(a)
print(set(a))

but I need it like this

output:
[0, 22, 2, 3, 44, 5, 6, 27, 8, 19]
{0, 2, 3, 5, 6, 8, 44, 19, 22, 27}

for getting this kind of output I can use list with for.. too with bellow cade or by method ( removing duplicates from list ).. there are many ways.. but

lis = []
for i in a:
  if i in lis:
    lis.append(i)
print(lis)
output:
[0, 22, 2, 3, 44, 5, 6, 27, 8, 19]

but the thing is I need to get this kind of output in set function, and give me the reason why it is changing in order.. or who this transformation workes ???

Ares_5919
  • 1
  • 1

1 Answers1

2

This is covered in the Python documentation. A set uses a hash-table structure internally to make for faster lookups. Enumerating that table does not retain the insertion order.

You can do this with a dict, which does happen to retain insertion order in Python 3.6 and beyond.

a = list(dict((i,1) for i in a))
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 1
    `list(dict.fromkeys(a))` ;) – mozway Aug 25 '22 at 18:42
  • Might be worth mentioning that dictionary order is only guaranteed in versions 3.6+ just in case – G. Anderson Aug 25 '22 at 18:43
  • 1
    Unless there's a weird definition of "tree structure" I'm not familiar with, Python `set`s do not use a tree structure. They're hash tables, flat arrays that perform lookups by taking the object's hash code modulo the number of elements in the array, then doing some fun jumping around when collisions occur to find a valid slot that will be findable on future lookups. – ShadowRanger Aug 25 '22 at 18:45
  • 2
    @G.Anderson: More precisely, it's an implementation detail of the CPython reference interpreter for 3.6, and only becomes a language guarantee for Python 3.7. If you need to support older Python, you stick to `collections.OrderedDict`, e.g. `list(OrderedDict.fromkeys(a))`. – ShadowRanger Aug 25 '22 at 18:47
  • You're right about hash vs tree. My mental lapse. – Tim Roberts Aug 25 '22 at 19:31