Every array is born in two ways: from data you already have, or generated on the fly, with the shape you request. NumPy has a function for almost every situation.
Code for this chapter: básico/cap05_criando_arrays.py
From your data
The np.array converts lists (and lists of lists) into an array. Nested lists become dimensions:
All rows need to be the same size. An array is a rectangular grid, and NumPy refuses an "irregular" structure instead of guessing what you meant:
básico/cap05_criando_arrays.pylinhas 15 a 18
try:np.array([[1,2],[3]])exceptValueErroraserro:print("erro de forma irregular:","inhomogeneous"instr(erro))
Output
erro de forma irregular: True
Filling arrays: you provide the shape
When you don't have the values yet, but know the shape, fill arrays reserve the space. The shape is a tuple, and that’s where the most common mistake lies:
Writing np.zeros(2, 3), NumPy understands the 3 as the data type (the second parameter), and that’s why the message refers to "data type". The form is a single argument: np.zeros((2, 3)), with double parentheses.
The np.empty also reserves the form, but does not initialize the memory: the content is what was already there, not zero. It is a bit faster than the zeros, and only serves when you are going to overwrite all the values right after. I rarely use it because the gain is small and the risk of reading garbage is real.
The np.eye(3) is the identity matrix (ones on the diagonal). The np.diag builds a diagonal matrix from a list, and if it receives a matrix, it does the reverse and extracts the diagonal.
The arange works like the range of Python: start, end (excluded), and step. The linspace receives the number of points and includes both extremes. The logspace spaces the points on a logarithmic scale, from 10⁰ to 10², three points.
arange with decimal step
With decimal steps, the arange accumulates floating-point error and can surprise you with the size of the result. When you know how many points you want, the linspace is more predictable: