1

When I do:

set('zbc')

I get as a result:

{'b' , 'z' , 'c'}

And when I start another python code and type the same thing, I get different order? Why is that? Is there a way to get the same order everytime? thanks.

CodeCop
  • 1
  • 2
  • 15
  • 37
  • Please repeat [how to ask](https://stackoverflow.com/help/how-to-ask) from the intro tour. This is covered in the `set` documentation and many, many places on line. We expect you to do your research before posting here. – Prune Apr 12 '20 at 06:06
  • @SendHelp `set` doesn't maintain the order – deadshot Apr 12 '20 at 06:06
  • @Prune Hey prune, thanks for your comment, aside from the "why" question - I asked if we have an option to keep the order, so this is not a "ask to ask" question.. – CodeCop Apr 12 '20 at 06:11
  • Your second question is also covered with a straightforward browser search. – Prune Apr 12 '20 at 06:59

2 Answers2

2

Just read this documentation

Sets are unordered collection.

You can use other modules like OrderedDict

from collections import OrderedDict 
od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4

for key, value in od.items(): 
    print(key, value) 

Output :

('a', 1)
('b', 2)
('c', 3)
('d', 4)
Lovleen Kaur
  • 342
  • 2
  • 9
0

Order in set is not guaranteed as they are based on hash tables and not on balanced trees.

Moreover hashing is randomized when Python starts to avoid denial of service attacks to servers: carefully crafted requests could put servers in O(n) search times on dictionaries making servers unable to answer in time.

dict on the other hand has been changed recently and it maintains the insertion order; thus if you only insert elements and later iterated the dictionary the key/value pairs will be in the same order they were when you inserted them.

Instead of a set like

{'c', 'b', 'z'}

you can use a dict like

{'c': None, 'b': None, 'z': None}

on recent CPython the key sequence will be c, b and z (not sure if other Python implementations already aligned on this).

6502
  • 112,025
  • 15
  • 165
  • 265
  • is there a way to keep the order from first to last- meaning that if I type zbc the output will be {z,b,c} and when I type cbz the output will be {c,b,z} ? thanks for the explanation ! – CodeCop Apr 12 '20 at 06:10
  • @SendHelp: you can use a `dict` with `None` as values; in recent cpython version this will maintain sequence as it does for example in Javascript. – 6502 Apr 12 '20 at 06:17
  • awesome, thank you! – CodeCop Apr 12 '20 at 06:18