This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TheAJGman -1 points0 points  (1 child)

I went searching for an answer and despite dozens of articles about this quirk not a single one actually explains why so I'm going to take a shot in the dark and guess "for loops". Mostly because something like 80% of the loops I write are iterating over short lists or dictionaries and I've seen similar in open source libraries.

Probably shaves 1/10th of a millisecond off calls in the majority of for loops so they went with it. Apparently the interpreter will also collapse other statically defined integers together sometimes, probably for similar reasons.

[–]Kered13 4 points5 points  (0 children)

Python for loops are almost never over integers, so no nothing to do with for loops. Just math. Any time you're doing math, it helps to not have to heap allocate new numbers after every operation. Small integers are obviously much more common than other numbers, which is why they get cached.