Ask Your Question
0

Difference between Python and SageMath: operator ^ does not work for sets

asked 2026-07-02 07:09:59 +0200

ortollj gravatar image

In standard Python, the operator ^ is overloaded for set objects and performs the symmetric difference:

{1, 2, 3} ^ {3, 4, 5} # returns {1, 2, 4, 5} However, in SageMath, the same expression raises an error:

A = {1, 2, 3}
B = {3, 4, 5}

def test():
    print("hello")
    C = A ^ B
    return C

test()

Result:

hello TypeError: unsupported operand type(s) for ** or pow(): 'set' and 'set' This is surprising because:

the traceback shows ** instead of ^, the error message refers to exponentiation (pow), the line number corresponds to the correct location, but the operator displayed is not the one written in the code. This suggests that SageMath does not overload ^ for sets (unlike Python), and internally treats ^ as the exponentiation operator, even when applied to sets. The resulting error message is therefore misleading.

Workaround Use the explicit symmetric difference:

A.symmetric_difference(B)

or implement XOR manually:

def xorF(s0, s1):
    return (s0 - s1) | (s1 - s0)

Question Is this behavior intentional in SageMath? Should SageMath overload ^ for sets as Python does, or at least provide a clearer error message?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2026-07-02 18:26:25 +0200

updated 2026-07-02 18:27:48 +0200

This is intentional, and it's part of the SageMath preparser, which automatically converts "^" to "**". One way to get around this is to turn it off:

A = {1, 2, 3}
B = {3, 4, 5}
preparser(False) # turn off preparsing when Sage reads the function definition

def test():
    print("hello")
    C = A ^ B
    return C

preparser(True) # safe to turn it back on now
test()
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2026-07-02 07:09:59 +0200

Seen: 17 times

Last updated: 5 hours ago