Member-only story
Most Weird Things in Python
Python is a great language but perfect and it has special features that the developers can’t understand.
257 is not 257
Why it is happened? Python has pre-loaded integers in the memory of [-5, 256] and they have been loaded in the memory and we don’t create new objects in this range.
Therefore, when the variables a and b were created, they refer to the same memory location returning the same id, while as you can see x and y are two different objects in different memory locations.
Floating-point precision (0.1 + 0.2 != 0.3)
Python uses a 32-bit floating point for the number, and with decimal fractions, this floating-point number system causes some rounding errors as 1.2 is not 1.20000 but 1.1999999999999999555910790149937383830547332763671875. To resolve this fraction and potential error, we can use Number.Epsilon function as it will return the smallest ‘interval’.
a+=1 is faster than a = a+1
The difference is marginal for sure and Python is not the language chosen for the performance. Just to resolve curiosity, why += statement is faster? The answer is the difference between INPLACE_ADD and BINARY_ADD.
If we do += behind the scenes, you will be able to see below.
# If we do += behind scene, you will be able to see
LOAD_FAST 0 (a)
LOAD_CONST 2 (1)…