-1

Code: a={1,2,3} c={14,62} b=a|c print(b) Output: {1,2,3,14,62}

Code: a={1,2,3} c={15,62} b=a|c print(b) Output: {1,2,3,62,15}

Code: a={1,2,3} c={16,62} b=a|c print(b) Output: {16,1,2,3,62}

Code: a={1,2,3} c={17,62} b=a|c print(b) Output: {1,2,3,17,62}

Code: a={12} c={4} b=a|c print(b) Output: {12,43}

Code: a={12} c={44} b=a|c print(b) Output: {44,12}

Why is that the resultant set is ordered most of the time but not in some cases. Numbers like 15,31,63 (00001111,0001111,0011111111) are always at end and numbers like 16,32,64 (00010000,00100000,01000000) are at first position. Explain please.

  • 1
    Set order is **not** guaranteed. – jonrsharpe Sep 16 '18 at 16:36
  • 2
    Welcome to StackOverflow. That operation is not "bit-wise OR" even if it uses the same character. For sets, that is the union operation. In Python, sets are by definition not ordered, so you are not guaranteed to get any specific order at all in your printout of the set. If you need a certain order, you could sort the set, resulting in a list, before you print. Or, in the current version of Python, you could simulate sets with a dictionary or other data container. – Rory Daulton Sep 16 '18 at 16:36
  • But if the set order is not guaranteed then why is output always the same and is following the pattern I wrote about in the end – Prateek Sah Sep 16 '18 at 16:51
  • The result is not guaranteed means that it could be whatever it is (in particular, it may look ordered), but you should not make any assumptions about the order. – DYZ Sep 16 '18 at 16:55

1 Answers1

3

That's not bitwise OR even if it looks alike. That's set.union().

Also, the order of elements in a set has no guarantee. You may not expect any order unless you convert it to a list and sort it.

See Python 3 documentation on set.union().

iBug
  • 35,554
  • 7
  • 89
  • 134