Introduction to NumPy
Overview
NumPy (Numerical Python) is a Python library for fast numerical computing built around the ndarray, an array whose elements all share one data type. This chapter explains why arrays are faster and more compact than lists and shows how to create 1-D and 2-D NumPy arrays from Python lists with np.array(), including how data types are chosen and converted. Further features of arrays are given as enrichment.
The CBSE 2025-26 syllabus includes only Introduction to NumPy and Creation of NumPy Arrays from List. Array attributes, other creation functions, indexing, slicing, operations, statistics and loading from files are marked (Enrichment) in these notes; they are useful background for Pandas in Class XII but are not examined.
Learning outcomes
- Students will be able to explain what NumPy is and why it is used for numerical work.
- Students will be able to state the characteristics of an array and compare a NumPy array with a Python list.
- Students will be able to import NumPy using the alias
np. - Students will be able to create 1-D arrays from lists and 2-D arrays from nested lists using
np.array(). - Students will be able to predict the data type of an array created from a list of mixed values (type promotion).
- Students will be able to set the data type of a new array using the
dtypeargument. - Students will be able to identify and correct common errors while creating arrays.
- Students will be able to use basic array attributes such as
shape,ndimanddtypeto check an array (enrichment).
Lesson plan
Write a list of 5 marks on the board and ask students to add 5 grace marks to each using a list. They need a loop. Then show np.array(marks) + 5 on the projector. Discuss arrays: same data type, contiguous memory, zero-based index. Students note the list-vs-array comparison table.
In the lab students run pip install numpy (if needed) and import numpy as np. They create 1-D arrays of runs, prices and temperatures from lists and print type() and dtype of each.
Prediction game: the teacher writes a list on the board (e.g. [4, 7.5, 9] or [5, 'R', 3]). Students write the expected output and dtype before running it. Then use dtype=float, dtype=int and dtype=str and discuss what changes.
Students take a 3 x 4 marks table (3 students, 4 subjects) from their notebook, type it as a nested list and convert it to a 2-D array. Discuss rows and columns, shape, and the error for rows of unequal length.
Debugging round: give five buggy lines such as np.array(1, 2, 3) and import Numpy as np; pairs fix them. Then demonstrate ndim, shape, size, dtype, itemsize.
A quick demonstration of zeros, ones, arange, indexing, slicing and mean() to show what lies ahead in Class XII. Students then complete the practicals and the MCQ worksheet.
Notes
What is NumPy?
NumPy stands for Numerical Python. It is an open-source Python library (package) for scientific computing and data analysis.
Key points:
- Its main object is the ndarray (n-dimensional array), commonly just called an array.
- Arrays let us store large amounts of numerical data and process all of it at once, without writing loops.
- NumPy is very fast because its core is written in C.
- Other libraries such as Pandas and Matplotlib (Class XII) are built on top of NumPy.
NumPy does not come with Python. Install it once from the command prompt:
pip install numpy
Then import it in every program. By convention we use the short name (alias) np.
import numpy as np
print("NumPy version:", np.__version__)
marks = np.array([78, 85, 62, 90])
print(marks)
print(type(marks))NumPy version: 2.5.4 [78 85 62 90] <class 'numpy.ndarray'>
The package name is all lowercase: import numpy as np. import NumPy gives ModuleNotFoundError.
What is an array?
An array is a data structure that stores many values under a single name, where:
- every element has the same data type;
- elements are stored contiguously (one after another) in memory, which makes processing fast;
- each element is reached by its index (position), which starts from 0.
For the array [45, 12, 78, 33], 45 is at index 0, 12 at index 1, and 33 (the last element) at index 3. This zero-based indexing is the same as for lists.
Board question: State any two characteristics of an array. Answer with "same data type" and "contiguous memory" or "zero-based indexing".
NumPy array vs Python list
Lists and arrays both store many values, but they behave differently. The most visible difference: arithmetic on an array works element-wise (on every element), while * on a list repeats the list.
| Python list | NumPy array (ndarray) |
|---|---|
Elements can be of different types, e.g. [1, 'a', 2.5] | All elements are of the same type |
| Elements are not stored contiguously | Elements are stored contiguously, so operations are faster |
No element-wise arithmetic; L * 2 repeats the list | Element-wise arithmetic; A * 2 doubles every element |
| Uses more memory, since type information is kept for every element | Uses less memory; one data type is stored for the whole array |
| Part of core Python; no import needed | Part of the NumPy library; needs import numpy |
import numpy as np
price_list = [20, 35, 50]
price_arr = np.array([20, 35, 50])
print("list * 2 :", price_list * 2) # repeats the list
print("array * 2 :", price_arr * 2) # doubles every element
print("array + 5 :", price_arr + 5)
print("array / 5 :", price_arr / 5)list * 2 : [20, 35, 50, 20, 35, 50] array * 2 : [ 40 70 100] array + 5 : [25 40 55] array / 5 : [ 4. 7. 10.]
Creating a 1-D array from a list
The function np.array() converts a list (or tuple) into a NumPy array. An array with a single row of elements is a one-dimensional (1-D) array.
Syntax: numpy.array(object, dtype=None)
object: a list, tuple or nested list of valuesdtype(optional): the data type of the elements
When printed, an array shows its elements separated by spaces, without commas, which is how you can tell it apart from a list.
import numpy as np
runs = [45, 12, 78, 33] # a Python list
a = np.array(runs) # 1-D array from the list
print(a)
print(a.dtype)
temps = np.array([31.5, 29.0, 33.2]) # list written directly inside array()
print(temps)
print(temps.dtype)[45 12 78 33] int64 [31.5 29. 33.2] float64
On some Windows computers with older NumPy, integer arrays show int32 instead of int64. Both are integer types; accept either in answers.
Type promotion: lists with mixed values
Since all elements of an array must have one type, NumPy picks a type that can hold every value in the list and converts (promotes, or upcasts) the others to it:
bool<int<float<str(string is the most general)- int and float mixed -> all become float
- bool and int mixed -> all become int (
True-> 1,False-> 0) - if even one string is present -> every element becomes a string (dtype like
<U32, meaning Unicode text up to 32 characters)
Once numbers become strings, arithmetic on them no longer works.
import numpy as np
a = np.array([4, 7.5, 9]) # int and float mixed
print(a, a.dtype)
b = np.array([1, 0, True]) # bool with int
print(b, b.dtype)
c = np.array([5, -7.4, 'R', 3]) # a string is present
print(c)
print(c.dtype)[4. 7.5 9. ] float64 [1 0 1] int64 ['5' '-7.4' 'R' '3'] <U32
A favourite output question: predict the output of np.array([1, 2.0, 3]). Answer: [1. 2. 3.], with a dot after each number to show float.
Creating a 2-D array from a nested list
A two-dimensional (2-D) array has rows and columns, like a table. Create it by passing a nested list (a list of lists) to np.array(); each inner list becomes one row.
Rules:
- every inner list must have the same number of elements;
- the same type promotion applies to the whole array.
import numpy as np
# marks of 3 students in 4 subjects: each inner list is one row
marks = [[78, 85, 62, 90],
[55, 67, 71, 80],
[92, 88, 95, 91]]
m = np.array(marks)
print(m)
print("Rows and columns:", m.shape)
mixed = np.array([[1.5, 2], [3, 4]]) # ints promoted to float
print(mixed)[[78 85 62 90] [55 67 71 80] [92 88 95 91]] Rows and columns: (3, 4) [[1.5 2. ] [3. 4. ]]
Choosing the data type with dtype
The dtype argument of np.array() converts every value of the list to the type we ask for:
dtype=float: integers become floatsdtype=int: floats are truncated (decimal part cut off, not rounded), so 2.9 becomes 2 and −3.6 becomes −3dtype=str: numbers become text
import numpy as np
a = np.array([10, 20, 30], dtype=float)
print(a, a.dtype)
b = np.array([2.9, 7.1, -3.6], dtype=int) # decimal part is cut off
print(b, b.dtype)
c = np.array([1, 2, 3], dtype=str)
print(c, c.dtype)[10. 20. 30.] float64 [ 2 7 -3] int64 ['1' '2' '3'] <U1
Ask students: Is 7.1 stored as 7 or 8 with dtype=int? Truncation, not rounding, is a common trap.
Other things to know when creating arrays from lists
- A tuple can be passed instead of a list.
tolist()converts an array back into an ordinary Python list.- The values must be passed as one list argument.
np.array(1, 2, 3)is wrong;np.array([1, 2, 3])is correct. - A nested list with rows of unequal length cannot be made into a proper 2-D array; recent versions of NumPy raise a
ValueError.
import numpy as np
a = np.array([3, 6, 9])
back = a.tolist() # array -> Python list
print(back, type(back))
t = np.array((11, 22, 33)) # a tuple also works
print(t)[3, 6, 9] <class 'list'> [11 22 33]
Common errors while creating arrays
Passing values without square brackets gives an error, because the second argument of array() is the data type. The error text varies between NumPy versions, so focus on the fix.
import numpy as np
try:
a = np.array(1, 2, 3) # WRONG: values not inside a list
except TypeError as e:
print("TypeError:", e)
a = np.array([1, 2, 3]) # CORRECT: one list argument
print(a)TypeError: array() takes from 1 to 2 positional arguments but 3 were given [1 2 3]
Rows of unequal length
Each row of a 2-D array must have the same number of columns. If one inner list is shorter, the list is ragged and NumPy refuses to make a 2-D array from it.
import numpy as np
try:
r = np.array([[1, 2, 3], [4, 5]]) # rows of unequal length
except ValueError:
print("ValueError: rows must have the same length")ValueError: rows must have the same length
Older textbooks show such lists becoming an array of object type. Current NumPy versions raise an error instead.
Attributes of a NumPy array (Enrichment)
Attributes describe an array. They are written without brackets, because they are not functions.
ndim: number of dimensions (axes); 1 for 1-D, 2 for 2-D. In a 2-D array, axis 0 runs down the rows and axis 1 across the columns.shape: size in each dimension, as a tuple;(4,)for 4 elements,(2, 3)for 2 rows and 3 columns.size: total number of elements (product of the shape).dtype: data type of the elements.itemsize: bytes used by each element (8 forint64/float64, 4 forint32).
import numpy as np
a = np.array([10, 20, 30, 40])
m = np.array([[1.5, 2.0, 3.5],
[4.0, 5.5, 6.0]])
print("ndim :", a.ndim, m.ndim)
print("shape :", a.shape, m.shape)
print("size :", a.size, m.size)
print("dtype :", a.dtype, m.dtype)
print("itemsize:", a.itemsize, m.itemsize)ndim : 1 2 shape : (4,) (2, 3) size : 4 6 dtype : int64 float64 itemsize: 8 8
Other ways to create arrays (Enrichment)
np.zeros(shape): all elements 0 (float by default)np.ones(shape): all elements 1 (float by default)np.arange(start, stop, step): likerange(), but returns an array; stop is excludednp.linspace(start, stop, num): num equally spaced values, with stop included
import numpy as np
print(np.zeros((2, 3)))
print(np.ones((2, 2), dtype=int))
print(np.arange(5))
print(np.arange(10, 31, 5))
print(np.linspace(0, 1, 5))[[0. 0. 0.] [0. 0. 0.]] [[1 1] [1 1]] [0 1 2 3 4] [10 15 20 25 30] [0. 0.25 0.5 0.75 1. ]
Indexing and slicing (Enrichment)
1-D arrays are indexed and sliced like lists. For 2-D arrays, use [row, column], and slices like [r1:r2, c1:c2] (end positions excluded). A colon on its own (:) means "all rows" or "all columns".
import numpy as np
m = np.array([[78, 85, 62, 90],
[55, 67, 71, 80],
[92, 88, 95, 91]])
print(m[0, 2]) # row 0, column 2
print(m[2]) # whole row 2
print(m[-1, -1]) # last row, last column
print(m[0:2, 1:3]) # rows 0-1, columns 1-2
print(m[:, 0]) # first column of every row
a = np.array([5, 10, 15, 20, 25, 30])
print(a[1:5:2])
print(a[::-1])62 [92 88 95 91] 91 [[85 62] [67 71]] [78 55 92] [10 20] [30 25 20 15 10 5]
Operations on arrays (Enrichment)
Arithmetic operators (+ - * / // % **) work element-wise on arrays of the same shape. @ (or np.dot) does matrix multiplication. .T gives the transpose (rows become columns). np.sort() returns a sorted copy.
import numpy as np
a = np.array([[2, 4], [6, 8]])
b = np.array([[1, 2], [3, 4]])
print(a + b)
print(a * b) # element-wise, not matrix product
print(a ** 2)
print(a // b)
print(a @ b) # matrix multiplication
print(a.T) # transpose
print(np.sort(np.array([40, 10, 30, 20])))[[ 3 6] [ 9 12]] [[ 2 8] [18 32]] [[ 4 16] [36 64]] [[2 2] [2 2]] [[14 20] [30 44]] [[2 6] [4 8]] [10 20 30 40]
Concatenating, reshaping and splitting (Enrichment)
np.concatenate((a, b), axis=0)joins arrays one below the other;axis=1joins them side by side. The other dimension must match.reshape(r, c)gives the same data a new shape; r x c must equal the number of elements.np.split(a, n)divides an array into n equal parts.
import numpy as np
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6]])
print(np.concatenate((x, y), axis=0))
a = np.arange(1, 7)
r = a.reshape(2, 3)
print(r)
parts = np.split(np.arange(9), 3)
print(parts[0], parts[1], parts[2])[[1 2] [3 4] [5 6]] [[1 2 3] [4 5 6]] [0 1 2] [3 4 5] [6 7 8]
Statistical operations (Enrichment)
max(), min(), sum(), mean() and std() work on the whole array, or along an axis: axis=0 works down each column, axis=1 across each row. These are the same operations Pandas uses on DataFrame columns in Class XII.
import numpy as np
m = np.array([[78, 85, 62],
[55, 67, 71],
[92, 88, 95]])
print("Max :", m.max())
print("Min per col :", m.min(axis=0))
print("Sum per row :", m.sum(axis=1))
print("Mean :", round(m.mean(), 2))
print("Std dev :", round(m.std(), 2))Max : 95 Min per col : [55 67 62] Sum per row : [225 193 275] Mean : 77.0 Std dev : 13.25
Loading arrays from files (Enrichment)
np.loadtxt(file, delimiter=',', skiprows=1, dtype=...)reads a clean text/CSV file with no missing values.skiprows=1skips the header row.np.genfromtxt(file, delimiter=',', filling_values=...)also handles missing values: they becomenan, or the value given infilling_values.
np.savetxt() writes an array to a file. In Class XII, Pandas read_csv() does the same job more easily.
import numpy as np
# create a small CSV file first (normally it already exists)
with open("scores.csv", "w") as f:
f.write("RollNo,Maths,Science,IP\n")
f.write("1,78,85,90\n")
f.write("2,55,67,80\n")
f.write("3,92,88,95\n")
data = np.loadtxt("scores.csv", delimiter=",", skiprows=1, dtype=int)
print(data)
print("IP column:", data[:, 3])
with open("gaps.csv", "w") as f:
f.write("1,78,85\n2,,67\n")
g = np.genfromtxt("gaps.csv", delimiter=",", filling_values=-1)
print(g)[[ 1 78 85 90] [ 2 55 67 80] [ 3 92 88 95]] IP column: [90 80 95] [[ 1. 78. 85.] [ 2. -1. 67.]]
Key terms
- NumPy
- Numerical Python: a library for fast numerical computing with arrays.
- Library / package
- A ready-made collection of modules and functions that can be imported into a program.
- Array
- An ordered collection of elements of the same data type stored contiguously in memory.
- ndarray
- NumPy's n-dimensional array object; the official name of a NumPy array.
- np.array()
- NumPy function that creates an array from a list, tuple or nested list.
- 1-D array
- An array with a single row of elements; one axis.
- 2-D array
- An array with rows and columns, created from a nested list; two axes.
- Nested list
- A list whose elements are themselves lists.
- dtype
- The data type of the elements of an array, e.g. int64, float64, <U32.
- Type promotion (upcasting)
- Automatic conversion of all elements to the most general type present in the list.
- Contiguous memory
- Elements stored next to each other in memory without gaps.
- Element-wise operation
- An operation applied to each element of an array separately.
- Zero-based indexing
- Numbering positions from 0, so the first element has index 0.
- Alias
- A short alternative name for an imported module, e.g. np for numpy.
- shape
- Attribute giving the size of an array in each dimension, as a tuple (enrichment).
- Axis
- A dimension of an array; axis 0 runs down the rows, axis 1 across the columns (enrichment).
MCQs
Tap an option to check it, or use Show answers above to reveal them all.
-
NumPy stands for:
Answer(d) Numerical Python
NumPy is short for Numerical Python.
-
Which statement correctly imports NumPy with its usual alias?
Answer(a) import numpy as np
The module name is lowercase
numpy;npis the conventional alias. -
Which function creates a NumPy array from a list?
Answer(c) np.array()
np.array()converts a list, tuple or nested list into an ndarray. -
Which of these is TRUE for every NumPy array?
Answer(c) All its elements have the same data type
An array is homogeneous; indexing starts from 0 and it comes from the NumPy library.
-
What is the output?
import numpy as npprint(np.array([2, 4.5, 6]))Answer(c) [2. 4.5 6. ]
Int and float are mixed, so every element is promoted to float and printed with a decimal point. Elements are separated by spaces.
-
What will be the dtype of
np.array([3, 'a', 4.5])?Answer(a) Unicode string, e.g. <U32
If even one string is present, every element is converted to a string.
-
If
L = [5, 10]andA = np.array([5, 10]), what areL * 2andA * 2?Answer(d) [5, 10, 5, 10] and [10 20]
*repeats a list but multiplies each array element. -
What is the output of
print(np.array([3.9, -2.7], dtype=int))?Answer(d) [3 -2]
Converting to int truncates the decimal part: 3.9 becomes 3 and −2.7 becomes −2.
-
Which statement creates a 2-D array with 2 rows and 3 columns?
Answer(b) np.array([[1, 2, 3], [4, 5, 6]])
A nested list with 2 inner lists of 3 elements each gives 2 rows and 3 columns. Option C gives 3 rows and 2 columns.
-
Elements of a NumPy array are stored:
Answer(a) Contiguously in memory
Contiguous storage is one reason arrays are faster than lists.
-
Which statement about lists and NumPy arrays is FALSE?
Answer(d) A list must be imported from the NumPy library
Lists are built into Python; only arrays need NumPy.
-
What does
np.array([True, 0, 5])produce?Answer(c) [1 0 5]
bool mixed with int is promoted to int, so True becomes 1.
-
Which command installs NumPy?
Answer(a) pip install numpy
pip install numpyis run once at the command prompt;import numpyis used inside a program. -
The index of the last element of
np.array([7, 14, 21, 28, 35])is:Answer(d) 4
With zero-based indexing, 5 elements have indexes 0 to 4. (Its negative index is −1.)
-
(Enrichment) For
m = np.array([[1, 2, 3], [4, 5, 6]]), what ism.shape?Answer(a) (2, 3)
2 rows and 3 columns.
-
(Enrichment) For the same
m, what ism.size?Answer(c) 6
size is the total number of elements: 2 x 3 = 6.
-
(Enrichment) What is the output of
print(np.arange(2, 11, 3))?Answer(b) [2 5 8]
Start at 2, step 3, and stop before 11: 2, 5, 8.
-
(Enrichment) Which function creates an array filled with 0s?
Answer(b) np.zeros()
np.zeros(shape)fills an array of the given shape with 0.0. -
(Enrichment) For
a = np.array([10, 20, 30, 40, 50]), what isa[1:4]?Answer(a) [20 30 40]
The slice includes index 1 up to, but not including, index 4.
-
(Enrichment) Which function reads a CSV file with missing values into an array?
Answer(b) np.genfromtxt()
genfromtxt()can fill missing values;loadtxt()expects complete data.
Assertion–Reason
Assertion (A):
np.array([4, 5.5, 6])creates an array of floating-point numbers.Reason (R): All elements of a NumPy array must be of the same data type, so integers are promoted to float.
Answer(A)
Both are true and R explains why the integers become floats.
Assertion (A): Arithmetic on NumPy arrays is generally faster than the same work done on lists with a loop.
Reason (R): NumPy array elements are stored contiguously and all have the same type.
Answer(A)
Contiguous, same-type storage is what allows NumPy's fast element-wise operations.
Assertion (A):
np.array(10, 20, 30)creates an array of three elements.Reason (R): The values to be stored must be passed to
np.array()as a single list or tuple.Answer(D)
A is false; this statement raises an error. R is true and gives the correct usage.
Assertion (A): A Python list can store an integer, a string and a float together.
Reason (R): A NumPy array can also store an integer, a string and a float without changing them.
Answer(C)
A is true. R is false: in an array the numbers would be converted to strings.
Assertion (A):
np.array([2.8, 5.9], dtype=int)gives[2 5].Reason (R): Converting a float to int in NumPy rounds it to the nearest whole number.
Answer(C)
A is true because the decimal part is truncated. R is false: there is no rounding.
Short answer
- 2 marks
What is NumPy? Write the statement to import it with the alias
np.AnswerNumPy (Numerical Python) is a Python library for scientific and numerical computing. Its main object is the n-dimensional array (ndarray), which stores same-type data and supports fast element-wise operations.
import numpy as np - 2 marks
State any two differences between a Python list and a NumPy array.
Answer- A list can hold elements of different data types; all elements of an array are of the same type.
- A list does not support element-wise arithmetic (
L * 2repeats it); an array does (A * 2doubles each element).
(Also accepted: arrays are stored contiguously and use less memory; a list is built into Python while an array needs NumPy.)
- 2 marks
Write a program to create a NumPy array from the list
[88, 92, 79, 95]and print it with its data type.AnswerUse
np.array()and thedtypeattribute.Python import numpy as np marks = [88, 92, 79, 95] arr = np.array(marks) print(arr) print(arr.dtype)Output[88 92 79 95] int64
- 2 marks
Predict the output:
import numpy as npa = np.array([1, 2, 3.5])b = np.array([1, 'two', 3])print(a)print(b)Answerahas a float, so all values become float.bhas a string, so all values become strings.Python import numpy as np a = np.array([1, 2, 3.5]) b = np.array([1, 'two', 3]) print(a) print(b)Output[1. 2. 3.5] ['1' 'two' '3']
- 2 marks
How is a 2-D array created from a list? Give an example of a 2 x 2 array.
AnswerPass a nested list to
np.array(); each inner list becomes one row, and all inner lists must have the same length.Python import numpy as np m = np.array([[10, 20], [30, 40]]) print(m)Output[[10 20] [30 40]]
- 2 marks
What is the purpose of the
dtypeargument innp.array()? Give an example.Answerdtypesets the data type of the elements; every value in the list is converted to that type.Python import numpy as np a = np.array([1, 2, 3], dtype=float) print(a)Output[1. 2. 3.]
- 2 marks
Find the error and correct it:
import Numpy as npa = np.array(5, 10, 15)Answer- The module name must be lowercase:
import numpy as np. - Values must be passed as a single list:
a = np.array([5, 10, 15]).
- The module name must be lowercase:
- 2 marks
Why are NumPy arrays faster and smaller in memory than lists?
AnswerArray elements all have one data type and are stored contiguously in memory, so NumPy does not keep separate type information for each element and can process the whole block at once in fast compiled code. List elements are separate Python objects stored at different places, each carrying its own type information.
- 2 marks
What will be the output?
import numpy as npL = [3, 6, 9]A = np.array(L)print(L + L)print(A + A)Answer+joins two lists, but adds two arrays element by element.Python import numpy as np L = [3, 6, 9] A = np.array(L) print(L + L) print(A + A)Output[3, 6, 9, 3, 6, 9] [ 6 12 18]
- 2 marks
Explain type promotion in NumPy with one example.
AnswerWhen a list has values of different types, NumPy converts all elements to the most general type present (bool -> int -> float -> string), because an array can hold only one data type. Example:
np.array([5, 2.5])gives[5. 2.5]; the integer 5 is promoted to float 5.0. - 2 marks
(Enrichment) Write the output of:
import numpy as npm = np.array([[4, 5, 6], [7, 8, 9]])print(m.ndim, m.shape, m.size)Answer2 dimensions, 2 rows x 3 columns, 6 elements.
Python import numpy as np m = np.array([[4, 5, 6], [7, 8, 9]]) print(m.ndim, m.shape, m.size)Output2 (2, 3) 6
- 2 marks
(Enrichment) Differentiate between
np.zeros((2, 3))andnp.ones((3, 2)).Answernp.zeros((2, 3))creates a 2-row, 3-column array filled with 0.0.np.ones((3, 2))creates a 3-row, 2-column array filled with 1.0. Both give float arrays by default.
Long answer
- 3 marks
Compare a Python list and a NumPy array on any three points, giving a small code example for one difference.
Answer- Data type: a list can mix types (
[1, 'a', 2.5]); an array holds one type, and mixed values are promoted. - Operations: lists have no element-wise arithmetic; arrays apply
+ - * /to every element. - Memory and speed: array elements are stored contiguously with a single type, so arrays use less memory and are faster; list elements are separate objects.
Example of point 2:
Python import numpy as np L = [2, 4, 6] A = np.array(L) print(L * 3) print(A * 3)Output[2, 4, 6, 2, 4, 6, 2, 4, 6] [ 6 12 18]
- Data type: a list can mix types (
- 3 marks
Write a program that stores the runs scored by a team in 5 overs,
[8, 12, 4, 15, 9], in a NumPy array. Print the array, its data type, and the array after adding 2 bonus runs to every over.AnswerPython import numpy as np runs = [8, 12, 4, 15, 9] arr = np.array(runs) print("Runs :", arr) print("Type :", arr.dtype) print("Bonus :", arr + 2)OutputRuns : [ 8 12 4 15 9] Type : int64 Bonus : [10 14 6 17 11]
- 3 marks
Predict the output of each statement and give a reason:
(a)
np.array([1, 0, 2.0])
(b)np.array([False, 7])
(c)np.array([4, '4'])Answer(a) Int and float are mixed, so all elements become float.
(b) bool and int are mixed, so all become int (False -> 0).
(c) A string is present, so all become strings.Python import numpy as np print(np.array([1, 0, 2.0])) print(np.array([False, 7])) print(np.array([4, '4']))Output[1. 0. 2.] [0 7] ['4' '4']
- 3 marks
The marks of 3 students in Physics, Chemistry and IP are given below. Write a program to create a 2-D NumPy array from a nested list, then print the array, the number of rows and columns, and the same array converted to float.
Aarav: 72, 65, 88
Ishita: 81, 79, 94
Kabir: 58, 62, 70AnswerPython import numpy as np marks = [[72, 65, 88], [81, 79, 94], [58, 62, 70]] m = np.array(marks) print(m) print("Rows:", m.shape[0], "Columns:", m.shape[1]) print(np.array(marks, dtype=float))Output[[72 65 88] [81 79 94] [58 62 70]] Rows: 3 Columns: 3 [[72. 65. 88.] [81. 79. 94.] [58. 62. 70.]]
- 5 marks
(a) What is an array? State its three characteristics. (b) Why is NumPy needed when Python already has lists? (c) Write the code to create a 1-D array of the daily rainfall (in mm)
[12.5, 0, 33.2, 7]and explain the dtype of the result.Answer(a) An array is an ordered collection of elements under one name, where (i) every element has the same data type, (ii) elements are stored contiguously in memory, and (iii) each element is accessed by a zero-based index.
(b) Lists are general-purpose and slow for numerical work: they cannot do element-wise arithmetic, take more memory and need loops. NumPy arrays are compact, fast, support element-wise operations without loops, and form the base for Pandas and Matplotlib.
(c) The list has a float, so the integers 0 and 7 are promoted and the dtype is
float64.Python import numpy as np rain = np.array([12.5, 0, 33.2, 7]) print(rain) print(rain.dtype)Output[12.5 0. 33.2 7. ] float64
- 5 marks
Explain the use of
np.array()to create (i) a 1-D array, (ii) a 2-D array, (iii) an array of a chosen data type. Write one example of each with its output. Also state one error a student may make while creating a 2-D array.Answer(i) Pass a flat list; (ii) pass a nested list whose inner lists all have the same length; (iii) pass
dtype=. A common error: inner lists of different lengths, e.g.[[1, 2], [3]], which raises aValueErrorin current NumPy.Python import numpy as np one = np.array([5, 10, 15]) two = np.array([[1, 2], [3, 4]]) typed = np.array([7, 8, 9], dtype=float) print(one) print(two) print(typed)Output[ 5 10 15] [[1 2] [3 4]] [7. 8. 9.]
- 3 marks
(Enrichment) Given
t = np.array([[30, 32, 31], [27, 29, 28]])(temperatures of two cities over three days), write statements to print: (a) the shape, (b) the temperature of the second city on the third day, (c) the first day's readings for both cities, (d) the maximum temperature in each row.AnswerPython import numpy as np t = np.array([[30, 32, 31], [27, 29, 28]]) print(t.shape) print(t[1, 2]) print(t[:, 0]) print(t.max(axis=1))Output(2, 3) 28 [30 27] [32 29]
Case-based
Riya runs a small online stationery store from Pune. She keeps the prices (in Rs) of five items in a Python list: prices = [45, 120, 15, 80, 250]. During the Diwali sale she wants to apply a 10% discount to every item. Her friend suggests NumPy.
- 1 mark
Write the statement to import NumPy and convert
pricesinto an array namedp.Answerimport numpy as npp = np.array(prices) - 1 mark
Write one statement that gives the discounted prices without using a loop.
Answerp * 0.9(orp - p * 0.10). Every element is multiplied, because array arithmetic is element-wise.Python import numpy as np prices = [45, 120, 15, 80, 250] p = np.array(prices) print(p * 0.9)Output[ 40.5 108. 13.5 72. 225. ]
- 1 mark
What would
prices * 0.9do on the original list? Why?AnswerIt raises a
TypeError. A list cannot be multiplied by a float; lists do not support element-wise arithmetic. (prices * 2would only repeat the list.) - 1 mark
Riya adds the item name to the list:
[45, 120, 'Pen', 80], and converts it withnp.array(). What happens to the numbers, and why is this a problem?AnswerBecause a string is present, all elements are converted to strings (dtype like
<U21). The numbers become text such as'45', so arithmetic like the discount no longer works. Keep names and prices in separate arrays (or use a Pandas DataFrame in Class XII).
A school's sports teacher records the 100 m sprint times (in seconds) of three house captains over three trials:
Agni: 13.2, 13.0, 12.8
Vayu: 12.9, 13.1, 12.7
Jal: 13.5, 13.3, 13.4
She wants to store them in a 2-D NumPy array, one row per captain.
- 1 mark
Write the code to create the array
timesfrom a nested list.Answerimport numpy as nptimes = np.array([[13.2, 13.0, 12.8], [12.9, 13.1, 12.7], [13.5, 13.3, 13.4]]) - 1 mark
What will be the shape and data type of
times?AnswerShape
(3, 3)(3 rows, 3 columns); data typefloat64. - 1 mark
If Jal's third trial was not recorded and the teacher typed only two values for that row, what would happen?
AnswerThe rows would have unequal lengths (3, 3, 2). NumPy cannot form a proper 2-D array from such a list and raises a
ValueErrorin current versions. - 1 mark
(Enrichment) Write a statement to print each captain's best (lowest) time.
Answertimes.min(axis=1)finds the minimum across each row.Python import numpy as np times = np.array([[13.2, 13.0, 12.8], [12.9, 13.1, 12.7], [13.5, 13.3, 13.4]]) print(times.min(axis=1))Output[12.8 12.7 13.3]
Practicals
1Canteen sales array
Store the canteen's sales for six days in a list. Convert it into a NumPy array and print the array, its type, data type, number of dimensions and number of elements. Also print the sales after a 10% increase, without using a loop.
import numpy as np
# weekly sales (in Rs) of a school canteen, Monday to Saturday
sales = [4200, 3850, 4600, 3975, 5100, 2800]
arr = np.array(sales)
print("Array :", arr)
print("Type :", type(arr))
print("Data type :", arr.dtype)
print("Dimensions :", arr.ndim)
print("Elements :", arr.size)
print("Sales + 10%:", arr * 1.1)Array : [4200 3850 4600 3975 5100 2800] Type : <class 'numpy.ndarray'> Data type : int64 Dimensions : 1 Elements : 6 Sales + 10%: [4620. 4235. 5060. 4372.5 5610. 3080. ]
Viva questions (4)
- Which function converts a list to an array? np.array()
- Why did the increased sales print as decimals? Multiplying by 1.1 gives float results, so the new array is float.
- What does ndim = 1 tell you? The array is one-dimensional (a single row).
- Is
sizea function or an attribute? An attribute, so it is written without brackets.
22-D array of term marks
Store the marks of four students in three terms as a nested list. Create a 2-D NumPy array from it and print the array, its shape, number of rows, number of columns and data type. Then create the same array with dtype=float.
import numpy as np
# rows: students, columns: Term 1, Term 2, Term 3 marks
marks = [[67, 72, 80],
[88, 91, 85],
[54, 60, 58],
[75, 70, 79]]
m = np.array(marks)
print(m)
print("Shape :", m.shape)
print("Rows :", m.shape[0])
print("Columns :", m.shape[1])
print("Data type :", m.dtype)
f = np.array(marks, dtype=float)
print(f)[[67 72 80] [88 91 85] [54 60 58] [75 70 79]] Shape : (4, 3) Rows : 4 Columns : 3 Data type : int64 [[67. 72. 80.] [88. 91. 85.] [54. 60. 58.] [75. 70. 79.]]
Viva questions (4)
- What does each inner list become in the array? One row.
- What would happen if one student had only two term marks? The rows would be unequal and NumPy would raise an error.
- How do you read the number of columns from shape? It is shape[1].
- How is the float array printed differently? Each value shows a decimal point, e.g. 67.
3Type promotion explorer
Write a program that converts each of these lists to a NumPy array and prints the list, the array and its dtype: [10, 20, 30], [1.5, 2, 3], [1, 2.5, 'three'], [True, False, 1]. Write one line explaining each result.
import numpy as np
lists = [
[10, 20, 30],
[1.5, 2, 3],
[1, 2.5, 'three'],
[True, False, 1],
]
for L in lists:
a = np.array(L)
print(L, "->", a, a.dtype)[10, 20, 30] -> [10 20 30] int64 [1.5, 2, 3] -> [1.5 2. 3. ] float64 [1, 2.5, 'three'] -> ['1' '2.5' 'three'] <U32 [True, False, 1] -> [1 0 1] int64
Viva questions (4)
- Why did the third list become all strings? One element is a string, which is the most general type.
- What does <U32 mean? A Unicode string of up to 32 characters.
- What happens to True and False when mixed with int? They become 1 and 0.
- Can you add 5 to the third array? No; its elements are strings, so arithmetic fails.
4City temperature report (Enrichment)
Store five days' maximum temperatures of Delhi, Mumbai and Chennai in a 2-D array (one row per city). Print each city's maximum, minimum and average, the hottest reading overall, and the day-wise average across cities.
import numpy as np
temps = np.array([[31, 33, 35, 34, 30], # Delhi
[28, 29, 29, 30, 31], # Mumbai
[33, 35, 36, 37, 34]]) # Chennai
cities = ["Delhi", "Mumbai", "Chennai"]
for i in range(3):
row = temps[i]
print(cities[i], "max:", row.max(), "min:", row.min(),
"avg:", row.mean())
print("Hottest reading overall:", temps.max())
print("Day-wise average:", temps.mean(axis=0).round(2))Delhi max: 35 min: 30 avg: 32.6 Mumbai max: 31 min: 28 avg: 29.4 Chennai max: 37 min: 33 avg: 35.0 Hottest reading overall: 37 Day-wise average: [30.67 32.33 33.33 33.67 31.67]
Viva questions (3)
- What does axis=0 mean in temps.mean(axis=0)? Work down each column, giving one value per day.
- How do you get the Mumbai row? temps[1]
- Why does the average print as a float? The mean divides a sum by a count, giving a float.
5Reshape and slice a grid (Enrichment)
Create an array of the numbers 1 to 12 with np.arange(). Reshape it into 3 rows and 4 columns. Print the second row, the last column, the middle 2 x 2 block from the first two rows, and the shape of its transpose.
import numpy as np
a = np.arange(1, 13)
print("Original :", a)
grid = a.reshape(3, 4)
print(grid)
print("Second row :", grid[1])
print("Last column :", grid[:, -1])
print("Middle 2x2 block :")
print(grid[0:2, 1:3])
print("Transpose shape :", grid.T.shape)Original : [ 1 2 3 4 5 6 7 8 9 10 11 12] [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Second row : [5 6 7 8] Last column : [ 4 8 12] Middle 2x2 block : [[2 3] [6 7]] Transpose shape : (4, 3)
Viva questions (3)
- Why can 12 numbers be reshaped to (3, 4) but not to (5, 3)? The product of the new shape must equal the number of elements.
- What does grid[:, -1] mean? All rows, last column.
- What does .T do? It swaps rows and columns (transpose).
Common mistakes
Writing
import Numpy as nporimport NumPy. Correction: the module name is lowercase:import numpy as np.Passing values separately:
np.array(1, 2, 3). Correction: pass one list:np.array([1, 2, 3]).Expecting
[1, 2.5, 3]to stay a mix of int and float. Correction: all elements become float:[1. 2.5 3. ].Assuming
dtype=introunds 7.8 to 8. Correction: conversion to int truncates, so 7.8 becomes 7.Creating a 2-D array from rows of different lengths. Correction: every inner list must have the same number of elements.
Thinking
list * 2andarray * 2do the same thing. Correction: the list is repeated; each array element is multiplied by 2.Writing
a.shape()with brackets. Correction:shape,ndim,sizeanddtypeare attributes, written without brackets.Writing the printed array with commas, like a list. Correction: a printed NumPy array separates its elements with spaces:
[10 20 30].