I'm working with sets and notice when I do:

``````s1 = set( ['a', 'b', 'c'])
s2 = set([1,2,3])

print s1.symmetric_difference(s2)``````

It prints it off as:

``set(['a', 1, 2, 3, 'c', 'b'])``

Is there any reason to why it displays it in the order of 'a', 1, 2, 3, 'c', 'b' and not simply 'a', 'b', 'c', 1, 2, 3? Or because sets are unordered it doesn't matter how it's printed and both would be the same?

Thanks!

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by pyTony

It is because of unorderedness, and the order in sets varies:

``````>>> s1 & s2
set([])
>>> s1 | s2
set(['a', 1, 'c', 'b', 3, 2])
>>> s1.symmetric_difference(s2)
set(['a', 1, 2, 3, 'c', 'b'])
>>>``````

Edited by pyTony: n/a

I see that both s1 | s2 and s1.symmetric_difference(s2) result in sets with the same values

``````>>> s1 | s2
set(['a', 1, 'c', 'b', 3, 2])
>>> s1.symmetric_difference(s2)
set(['a', 1, 2, 3, 'c', 'b'])``````

If asked, would saying set() be a correct answer for s1 | s2 and s1.symmetric_difference(s2) or does order matter then? Thanks!

No it is like ^, when sets have common elements:

``````>>> a= set(['a','b','c'])
>>> b= set(['e','d','c'])
>>> a & b
set(['c'])
>>> a | b
set(['a', 'c', 'b', 'e', 'd'])
>>> a.symmetric_difference(b)
set(['a', 'b', 'e', 'd'])
>>> a ^ b
set(['a', 'b', 'e', 'd'])``````

http://en.wikipedia.org/wiki/Symmetric_difference