For example
a = 12345 # id(a) = 140127713009936
a = 6789 # id(a) = 140127713010448
b = 12345 # id(b) = 140127713009936
How is it possible that Python remembers somehow that integer object with value 12345 was created before and gives reference to it instead of creating new object? I understand how it works for values -5 to 256, but why it works even work greater numbers (and also for strings, though I don't know if it's the same mechanism)?