1 of 6
An array is not a list
One block of memory, one type, one fixed shape -- and that is the whole reason it is fast.
A Python list is a row of pointers. Each entry points somewhere else in memory, each can be a different type, and the list can grow. That flexibility costs you: to add up a million of them, Python follows a million pointers and asks each object what addition means.
An array gives all of that up. It is one contiguous block of memory, every element the same type, in a fixed shape. Adding up a million of them is one loop in compiled code over adjacent bytes, with nothing to look up.
Everything else in this lesson follows from those three constraints:
- One type, so the type is decided when the array is made and applies to everything in it.
- Fixed shape, so appending means allocating a new block and copying.
- Contiguous, so a reshape is usually free and a transpose does not move anything.
The trade is deliberate. You lose the ability to hold anything you like, and you get arithmetic that runs at the speed of the machine rather than the speed of the interpreter.
This is also why an array of Python objects is a warning sign. If you see dtype=object, the array is holding pointers again and you have paid for the rigidity without getting the speed.