Why for loop in Python is slow and in Julia is fast?

This title is simplification of topic, but I think idea is clear. I learn Julia from exactly one year, try to learn some internals (hard topics to me), but still don’t have good, short answer to this important question.

Why Julia looks so much like Python, but code can be so much faster? I ask this question, because I probably make presentation about Julia to students, so this questions is relevant. I know about type system, JIT, I even try to learn some internals, but I still don’t get it.

Julia can reason about what types things will be in your program. It does this once up front, the very first time you call a function. This is called inference.

Python constantly has to stop and ask — “wait, what type are you?” — after nearly every step of the program before knowing what to do next. It has to do this every single time.

There’s far more to it, but that’s how I explain it. Simple example is the difference between summing Int[1,2,3] and Any[1,2,3]. The former is fast because Julia knows it’ll get Ints back, whereas the latter is more akin to Python because every time you index it Julia has to ask what it got before knowing what to do with it.


Thank you for this answer, it is good idea to put it in forefront. I apologized for not responding so long, not so easy time along the way.