Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 01

What Is NumPy

Meet NumPy and its ndarray: one type per array, math on every element without a loop, less memory than a list, and easy reshaping.

Intermediate25 min
What Is NumPy hero Module 23 Lesson 1

NumPy is the Python library for numeric arrays. Its main type is the ndarray, short for n-dimensional array. An ndarray is a grid of values that all share one type and sit side by side in one block of memory. pandas, Matplotlib, and most machine learning libraries are built on it, so it is the first step after core Python.

NumPy workflow from install to reshape

Install and import

On your computer, install NumPy once with pip install numpy. In a program, import it as np. In the playground on this page, NumPy loads the first time you run code that imports it. That first run can take a few seconds.

python
import numpy as np

print(np.__version__)

Output (your version may differ):

text
1.26.4

List versus ndarray

* on a list repeats the list. * on an ndarray multiplies each element. This is called a vector operation: you write the math once and NumPy applies it to every value without a Python loop.

python
import numpy as np

prices = [120, 80, 45]
arr = np.array(prices)

print(prices * 2)
print(arr * 2)
print(arr + 5)
print(type(arr))

Output:

text
[120, 80, 45, 120, 80, 45]
[240 160  90]
[125  85  50]
<class 'numpy.ndarray'>

One type per array

Every element of an ndarray has the same type, called its dtype. If you mix integers and floats, NumPy stores them all as floats. If you mix numbers and text, it stores everything as text. You only get a mixed object array when you ask for one.

python
import numpy as np

whole = np.array([1, 2, 3])
mixed = np.array([1, 2.5, 3])
text = np.array([1, "two", 3])
objects = np.array([1, "two", 3], dtype=object)

print(whole)
print(mixed, mixed.dtype)
print(text)
print(objects, objects.dtype)

Output:

text
[1 2 3]
[1.  2.5 3. ] float64
['1' 'two' '3']
[1 'two' 3] object

Why arrays are faster and smaller

A list stores references to separate Python objects. An ndarray stores raw numbers in one block, so a sum or product can run in compiled code over that block. The same block can also be read as a different shape without copying the values.

python
import numpy as np

arr = np.arange(6)
print(arr)
print(arr.reshape(2, 3))
print(arr.sum())

Output:

text
[0 1 2 3 4 5]
[[0 1 2]
 [3 4 5]]
15

Key takeaways

  • An ndarray holds one type, stored side by side in memory

  • Math on an array applies to every element

  • * repeats a list but multiplies an array

  • reshape shows the same values in a new shape

  • Next: Array Attributes

  • Previous: Interview Tips

Loading playground…

Check your understanding

What Is NumPy Quiz

What is the main array type in NumPy?

1 / 10