NumPy Tutorial for Beginners: Arrays, Maths and Filtering in Python
P12.2 How to Create NumPy Arrays: array, arange, zeros, linspace
Why. You need arrays from lists, ranges of numbers or empty starting arrays.
| Function | Gives | Example → result |
|---|---|---|
| np.array(list) | array from a list | np.array([1,2]) → [1 2] |
| np.arange(a, b) | a to b-1 | np.arange(1,5) → [1 2 3 4] |
| np.zeros(n) | n zeros | np.zeros(3) → [0. 0. 0.] |
| np.linspace(a, b, n) | n evenly spaced values | np.linspace(0,1,3) → [0. 0.5 1.] |
How to read this table: each row is one way to create an array, with a tiny example.
How.
Create and inspect
- Create the array.
- Check
.shape(size) and.dtype(type). - Read items by index like a list.
Worked example A — Create and check.
Step 1 — What we do. Monthly revenue (₹ lakh) of a retail chain.
Step 2 — Type and run this code.
import numpy as np
rev = np.array([12.5, 14.0, 13.2, 15.8])
print(rev)
print(rev.shape, rev.dtype)
print(rev[0], rev[-1])
Step 3 — Output you should see.
[12.5 14. 13.2 15.8]
(4,) float64
12.5 15.8
Step 4 — What it means. Shape (4,) means 4 values in one dimension. dtype float64 means decimal numbers.
Worked example B — Ranges and zeros.
Step 1 — What we do. Day numbers for a 7-day report and an empty counter array.
Step 2 — Type and run this code.
import numpy as np
days = np.arange(1, 8)
counts = np.zeros(7)
print(days)
print(counts)
Step 3 — Output you should see.
[1 2 3 4 5 6 7]
[0. 0. 0. 0. 0. 0. 0.]
Step 4 — What it means. arange works like range; zeros is a starting point you can fill later.
Ravindra Bagale's Tip
All values in an array share one dtype. If you mix numbers and text, everything becomes text — check .dtype after creating.
Ravindra Bagale's Tip – मराठी
Array मधल्या सगळ्या values चा एकच dtype असतो. Numbers आणि text मिसळले तर सगळं text होतं — बनवल्यावर .dtype तपासा.
Ravindra Bagale's Tip – हिंदी
Array की सारी values का एक ही dtype होता है. Numbers और text मिलाए तो सब text बन जाता है — बनाने के बाद .dtype check करो.