Strange python behavior

I was bored of playing with the ipython console and I came across the following behavior that I really don't understand.

In [1]: 2**2 Out[1]: 4 In [2]: 2**2**2 Out[2]: 16 In [3]: 2**2**2**2 Out[3]: 65536 In [4]: 2**2**2**2**2 

The answer to [4] is not 4294967296L, it is a very long number, but I cannot understand why.

The number can be found here: http://pastie.org/475714

(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)
(Mac OS X 10.5.6, Python 2.5.1)

+7
python ipython
source share
5 answers

Python goes left on a mathematical power operation. For example, IN [2] does:

2 ** (4) = 16

IN [3] = 2 2 2 2 = 2 2 ** (4) = 2 ** 16 = 65536

You will need a bracket if you want it to be calculated from left to right. The reason OUT [4] does not display the answer you want, because the number is astronomical, and Python cannot print it.

2 ^ 65536 = extremely huge

+16
source share

Operator Priority ** makes the assessment from right to left (instead of what is expected from left to right). In other words:

 2**2**2**2 == (2**(2**(2**2))) 
+7
source share

This is because the order of priority in Python makes this equation evaluate from right to left.

 >>> 2**2 4 >>> 2**2**2 16 >>> 2**(2**2) 16 >>> 2**2**2**2 65536 >>> 2**2**(2**2) 65536 >>> 2**(2**(2**2)) 65536 >>> 2**2**2**2**2 57896044618658097711785492504343953926634992332820282019728792003956564819968L >>> 2**2**2**(2**2) 57896044618658097711785492504343953926634992332820282019728792003956564819968L >>> 2**2**(2**(2**2)) 57896044618658097711785492504343953926634992332820282019728792003956564819968L >>> 2**(2**(2**(2**2))) 57896044618658097711785492504343953926634992332820282019728792003956564819968L >>> 2**255 57896044618658097711785492504343953926634992332820282019728792003956564819968L 
+4
source share

As the other answers have already said, this is because ** is evaluated from right to left. Here is a link where all priorities are described.

+4
source share

When evaluating right to left, let's look at the steps that Python takes to get the following answers:

 2**2 4 2**(2**2) 2**(4) 16 2**(2**(2**2)) 2**(2**(4)) 2**(16) 65536 2**(2**(2**(2**2))) 2**(2**(2**(4))) 2**(2**(16)) 2**(65536) 2.0035299304068464649790723515603e+19728 
+3
source share

All Articles