-1

can someone explain to me how the print command in python orders a set? I know that the order of a set is random, but why do I get a different output if I call the set by its name or by the print command? For example: test = {1,32,0,5,84,9} testhas the output {0, 1, 5, 9, 32, 84} but print(test) has the output {32, 1, 0, 5, 9, 84}

Thank you for your answers!

Sash
  • 30
  • 5
  • 1
    What do you mean by `test has the output {0, 1, 5, 9, 32, 84} `? The reason print(test) [has it's order](https://stackoverflow.com/questions/21701618/why-python-set-displays-in-same-order-if-sets-are-unordered) – DarrylG May 28 '20 at 16:15
  • You can't order a set. Check out [this answer](https://stackoverflow.com/a/55389242/8286364) for more information. – Adam Boinet May 28 '20 at 16:17
  • Does this answer your question? [Why python set displays in "same" order if sets are unordered?](https://stackoverflow.com/questions/21701618/why-python-set-displays-in-same-order-if-sets-are-unordered) – imbr May 28 '20 at 16:48
  • Yes, I know that I cannot order it. But the question is why get I a different output when I use the print command ? – Pferfferhausen May 28 '20 at 16:54

2 Answers2

1

Dictionary key & value pairs have no order within the Dictionary. The order they are listed when printed out is completely arbitrary. You can't index or create slices from Dictionaries.

They are unordered collections like Sets; unlike Lists and Tuples where order matters.

Hope you find this helpful

harsh jain
  • 395
  • 1
  • 3
  • 11
0

When you call test, it defaults orders the elements in list in an ascending manner, but when it prints, it has random order.

The reason is basically, whenever you try to print an unordered set, the normal print command or even if you iterate using loop, it will give you this kind of erroneous output.

Read more on this here, Python Sets