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!

Recommended Answers

All 3 Replies

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'])
>>>

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.