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

2 Answers

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

Comments

Thank for the answer John Palmieri. One small observation: in a Jupyter notebook, the preparser seems to run on the entire cell before execution, so preparser(False) does not prevent the ^ → * conversion inside a function defined in that cell. As a result, A ^ B still becomes A * B in the traceback.

This is not a major issue at all, but I thought it might be useful to mention for notebook users.

ortollj gravatar imageortollj ( 2026-07-03 12:44:32 +0200 )edit
0

answered 2026-07-06 15:42:38 +0200

Max Alekseyev gravatar image

Yes, it's intentional. Python's ^ is available in Sage as ^^.

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: 168 times

Last updated: Jul 06