Lesson 1 of 7

Arrays, dtypes, shapes and axes

An array trades away everything a list can do in return for speed. What it keeps -- one type, one shape, one block of memory -- is what the rest of this curriculum is written against.

Six ideas, and one skill: look at an expression and say what comes out of it, without running it. Shape errors are the most common way a training run dies, and they are all caught by that one habit.

Pick an idea from the list. Most come with a challenge that makes you predict rather than read.

Every board states an expression and asks what comes out. Nothing runs — that is the point. Reading a shape off the page is the skill; running it to find out is what you are trying to stop needing.

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.