Aimify IP Material
Class 11 · Chapter 6

Introduction to NumPy

Partly in syllabusUnit 2: Introduction to Python (25 marks)~6 periods
20 MCQs32 written Qs5 practicals

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 dtype argument.
  • 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, ndim and dtype to check an array (enrichment).

Lesson plan

Period 1
What is NumPy; what is an array

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.

Period 2
Installing and importing NumPy; 1-D arrays from lists

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.

Period 3
Type promotion and the dtype argument

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.

Period 4
2-D arrays from nested lists

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.

Period 5
Common errors; array attributes (enrichment)

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.

Period 6
Enrichment tour and practice

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.

Python
import numpy as np

print("NumPy version:", np.__version__)
marks = np.array([78, 85, 62, 90])
print(marks)
print(type(marks))
Output
NumPy version: 2.5.4
[78 85 62 90]
<class 'numpy.ndarray'>
Teacher tip

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.

Teacher tip

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 listNumPy 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 contiguouslyElements are stored contiguously, so operations are faster
No element-wise arithmetic; L * 2 repeats the listElement-wise arithmetic; A * 2 doubles every element
Uses more memory, since type information is kept for every elementUses less memory; one data type is stored for the whole array
Part of core Python; no import neededPart of the NumPy library; needs import numpy
Python
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)
Output
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 values
  • dtype (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.

Python
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)
Output
[45 12 78 33]
int64
[31.5 29.  33.2]
float64
Teacher tip

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.

Python
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)
Output
[4.  7.5 9. ] float64
[1 0 1] int64
['5' '-7.4' 'R' '3']
<U32
Teacher tip

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.
Python
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)
Output
[[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 floats
  • dtype=int: floats are truncated (decimal part cut off, not rounded), so 2.9 becomes 2 and −3.6 becomes −3
  • dtype=str: numbers become text
Python
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)
Output
[10. 20. 30.] float64
[ 2  7 -3] int64
['1' '2' '3'] <U1
Teacher tip

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.
Python
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)
Output
[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.

Python
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)
Output
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.

Python
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")
Output
ValueError: rows must have the same length
Teacher tip

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 for int64/float64, 4 for int32).
Python
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)
Output
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): like range(), but returns an array; stop is excluded
  • np.linspace(start, stop, num): num equally spaced values, with stop included
Python
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))
Output
[[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".

Python
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])
Output
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.

Python
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])))
Output
[[ 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=1 joins 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.
Python
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])
Output
[[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.

Python
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))
Output
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=1 skips the header row.
  • np.genfromtxt(file, delimiter=',', filling_values=...) also handles missing values: they become nan, or the value given in filling_values.

np.savetxt() writes an array to a file. In Class XII, Pandas read_csv() does the same job more easily.

Python
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)
Output
[[ 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.

  1. NumPy stands for:

    Answer

    (d) Numerical Python

    NumPy is short for Numerical Python.

  2. Which statement correctly imports NumPy with its usual alias?

    Answer

    (a) import numpy as np

    The module name is lowercase numpy; np is the conventional alias.

  3. 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.

  4. 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.

  5. What is the output?

    import numpy as np
    print(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.

  6. 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.

  7. If L = [5, 10] and A = np.array([5, 10]), what are L * 2 and A * 2?

    Answer

    (d) [5, 10, 5, 10] and [10 20]

    * repeats a list but multiplies each array element.

  8. 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.

  9. 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.

  10. Elements of a NumPy array are stored:

    Answer

    (a) Contiguously in memory

    Contiguous storage is one reason arrays are faster than lists.

  11. 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.

  12. 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.

  13. Which command installs NumPy?

    Answer

    (a) pip install numpy

    pip install numpy is run once at the command prompt; import numpy is used inside a program.

  14. 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.)

  15. (Enrichment) For m = np.array([[1, 2, 3], [4, 5, 6]]), what is m.shape?

    Answer

    (a) (2, 3)

    2 rows and 3 columns.

  16. (Enrichment) For the same m, what is m.size?

    Answer

    (c) 6

    size is the total number of elements: 2 x 3 = 6.

  17. (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.

  18. (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.

  19. (Enrichment) For a = np.array([10, 20, 30, 40, 50]), what is a[1:4]?

    Answer

    (a) [20 30 40]

    The slice includes index 1 up to, but not including, index 4.

  20. (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

Choose: (A) Both A and R are true and R is the correct explanation of A. (B) Both A and R are true but R is not the correct explanation of A. (C) A is true but R is false. (D) A is false but R is true.
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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

  1. 2 marks

    What is NumPy? Write the statement to import it with the alias np.

    Answer

    NumPy (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. 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 * 2 repeats it); an array does (A * 2 doubles each element).

    (Also accepted: arrays are stored contiguously and use less memory; a list is built into Python while an array needs NumPy.)

  3. 2 marks

    Write a program to create a NumPy array from the list [88, 92, 79, 95] and print it with its data type.

    Answer

    Use np.array() and the dtype attribute.

    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
  4. 2 marks

    Predict the output:

    import numpy as np
    a = np.array([1, 2, 3.5])
    b = np.array([1, 'two', 3])
    print(a)
    print(b)

    Answer

    a has a float, so all values become float. b has 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']
  5. 2 marks

    How is a 2-D array created from a list? Give an example of a 2 x 2 array.

    Answer

    Pass 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]]
  6. 2 marks

    What is the purpose of the dtype argument in np.array()? Give an example.

    Answer

    dtype sets 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.]
  7. 2 marks

    Find the error and correct it:

    import Numpy as np
    a = np.array(5, 10, 15)

    Answer
    1. The module name must be lowercase: import numpy as np.
    2. Values must be passed as a single list: a = np.array([5, 10, 15]).
  8. 2 marks

    Why are NumPy arrays faster and smaller in memory than lists?

    Answer

    Array 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.

  9. 2 marks

    What will be the output?

    import numpy as np
    L = [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]
  10. 2 marks

    Explain type promotion in NumPy with one example.

    Answer

    When 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.

  11. 2 marks

    (Enrichment) Write the output of:

    import numpy as np
    m = np.array([[4, 5, 6], [7, 8, 9]])
    print(m.ndim, m.shape, m.size)

    Answer

    2 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)
    Output
    2 (2, 3) 6
  12. 2 marks

    (Enrichment) Differentiate between np.zeros((2, 3)) and np.ones((3, 2)).

    Answer

    np.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

  1. 3 marks

    Compare a Python list and a NumPy array on any three points, giving a small code example for one difference.

    Answer
    1. Data type: a list can mix types ([1, 'a', 2.5]); an array holds one type, and mixed values are promoted.
    2. Operations: lists have no element-wise arithmetic; arrays apply + - * / to every element.
    3. 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]
  2. 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.

    Answer
    Python
    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)
    Output
    Runs   : [ 8 12  4 15  9]
    Type   : int64
    Bonus  : [10 14  6 17 11]
  3. 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']
  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, 70

    Answer
    Python
    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. 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
  6. 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 a ValueError in 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.]
  7. 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.

    Answer
    Python
    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

Case study 1

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. 1 mark

    Write the statement to import NumPy and convert prices into an array named p.

    Answer

    import numpy as np

    p = np.array(prices)

  2. 1 mark

    Write one statement that gives the discounted prices without using a loop.

    Answer

    p * 0.9 (or p - 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. ]
  3. 1 mark

    What would prices * 0.9 do on the original list? Why?

    Answer

    It raises a TypeError. A list cannot be multiplied by a float; lists do not support element-wise arithmetic. (prices * 2 would only repeat the list.)

  4. 1 mark

    Riya adds the item name to the list: [45, 120, 'Pen', 80], and converts it with np.array(). What happens to the numbers, and why is this a problem?

    Answer

    Because 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).

Case study 2

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. 1 mark

    Write the code to create the array times from a nested list.

    Answer

    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]])

  2. 1 mark

    What will be the shape and data type of times?

    Answer

    Shape (3, 3) (3 rows, 3 columns); data type float64.

  3. 1 mark

    If Jal's third trial was not recorded and the teacher typed only two values for that row, what would happen?

    Answer

    The rows would have unequal lengths (3, 3, 2). NumPy cannot form a proper 2-D array from such a list and raises a ValueError in current versions.

  4. 1 mark

    (Enrichment) Write a statement to print each captain's best (lowest) time.

    Answer

    times.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.

Solution
Python
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)
Output
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 size a 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.

Solution
Python
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)
Output
[[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.

Solution
Python
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)
Output
[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.

Solution
Python
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))
Output
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.

Solution
Python
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)
Output
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 np or import 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=int rounds 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 * 2 and array * 2 do the same thing. Correction: the list is repeated; each array element is multiplied by 2.

  • Writing a.shape() with brackets. Correction: shape, ndim, size and dtype are 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].