1

Why is ^ not squaring in Python? I know exponentiation is ** instead, but what exactly is ^ and why wasn't that operator used instead?

For example 2^2=0, 3^2=1.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
ZHU
  • 904
  • 1
  • 11
  • 25

2 Answers2

7

The ^ operator was already used for bitwise xor.

>>> x = 42; format(x, '08b')
'00101010'
>>> y = 137; format(y, '08b')
'10001001'
>>> z = x ^ y; format(z, '08b')
'10100011'

That leaves the old Fortran-style ** operator for exponentiation.

>>> base = 5
>>> exp = 2
>>> base ** exp
25
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
2

The "^" symbol in python is a bit-wise exclusive OR (XOR) operator. An OR gate is true if one of the inputs OR another is true. The XOR gate is true if and only if just a single input is true. 00 and 11 are false. 01 and 10 are true. The bit-wise XOR can be used to check how many bits differ.

For example,

  1. 2^2 = 10
    • ^10
      = 00
      = 0
  2. 3^2 = 11
    • ^10
      = 01
      = 1
Austin Mackillop
  • 1,165
  • 1
  • 10
  • 11