Your class has 40 students, and the teacher decides to give everyone 5 grace marks. With a Python list, you have to write a loop and add 5 to each student one by one. What if you could just write marks + 5 and have it done for all 40 students in one go? ๐ค That's exactly what NumPy does! ๐งฎ This chapter answers the BIG questions: What is NumPy and why do we need it? What is an array? How is a NumPy array different from a list? And how do we create a NumPy array from a list โ both 1-D and 2-D? Let's meet NumPy! ๐
The key topics are what NumPy is, what an array is, the differences between a list and a NumPy array, and creating arrays with np.array() from a list. Learn the list vs array table well โ "differentiate between" questions come straight from it. Then run every example yourself in the Python Lab and predict the output before you press Run!
8.1 ๐ Introduction โ What is NumPy?
NumPy stands for Numerical Python. It is a library (package) for Python that is used for working with arrays and doing fast calculations on numbers.
Full Form
NumPy stands for Numerical Python
Numerical PythonWhat it is
A free and open-source library that is added to Python
LibraryMain Object
Its main object is a fast array called ndarray
ndarrayCreated By
Travis Oliphant created NumPy in 2005
2005Analogy: Python is like a smartphone ๐ฑ. It can do a lot on its own, but when you need something special โ say, video editing โ you install an app. NumPy is Python's "maths app": you install it once, then import it whenever you want to work with lots of numbers quickly.
8.1.1 Why Do We Need NumPy? โญ
Fast
NumPy arrays are processed much faster than lists when there is a lot of data
SpeedLess Memory
Arrays store data compactly so they take less memory than lists
CompactMaths on All Items
One statement like marks + 5 works on every element at once without a loop
No loop neededBase for Other Libraries
Pandas and Matplotlib which you will study in Class 12 are built on NumPy
Pandas and MatplotlibNumPy is widely used in data analysis, science and engineering, and machine learning โ anywhere large amounts of numerical data have to be handled.
8.2 ๐ฅ Installing and Importing NumPy
NumPy does not come built into Python, so it has to be installed once. It is installed using pip (Python's package installer), typed at the command prompt, not inside Python:
pip install numpy
After that, we import it in every program that uses it:
import numpy as np
print("NumPy is ready!")
Output:
NumPy is ready!
Here np is an alias (a short nickname) for numpy. Instead of writing numpy.array(...) every time, we can simply write np.array(...). Using np is a convention followed by almost all Python programmers.
If you write np.array([1, 2, 3]) without first writing import numpy as np, Python gives NameError: name 'np' is not defined. And if NumPy is not installed at all, import numpy gives ModuleNotFoundError: No module named 'numpy'.
NumPy is like a library book โ you have to issue it (import numpy as np) before you can read it (np.array(...)).
8.3 ๐งฑ What is an Array?
An array is a collection of elements that are:
- all of the same data type (all integers, or all floats, or all strings), and
- stored next to each other (contiguously) in memory.
Each element can be reached by its index, which starts from 0 โ just like a list.
Index โ 0 1 2 3
โโโโโโโฌโโโโโโฌโโโโโโฌโโโโโโ
marks โ โ 45 โ 78 โ 92 โ 60 โ all integers, stored side by side
โโโโโโโดโโโโโโดโโโโโโดโโโโโโ
In NumPy, an array is called an ndarray, which stands for n-dimensional array. "n-dimensional" means it can have one dimension (a single row, like above), two dimensions (rows and columns, like a table), or more.
Analogy: A list is like your school bag ๐ โ you can put anything in it: books, a tiffin, a water bottle, a cricket ball. A NumPy array is like an egg tray ๐ฅ โ every slot is the same size and holds the same kind of thing, neatly in a row. Because everything is the same, you can deal with the whole tray at once!
8.4 โ๏ธ List vs NumPy Array
A list and a NumPy array both hold many values, but they behave very differently.
| Python List | NumPy Array |
|---|---|
| Built into Python โ no import needed | Needs import numpy as np |
| Can hold elements of different data types | All elements are of the same data type |
| Elements may not be stored next to each other in memory | Elements are stored contiguously (side by side) |
| Takes more memory | Takes less memory |
| Slower for large amounts of numerical data | Faster for numerical work |
| Maths on every element needs a loop | Maths works on every element at once (element-wise) |
Written as [10, 20, 30] |
Printed as [10 20 30] (no commas) |
See the difference in action:
import numpy as np
L = [10, 20, 30]
A = np.array([10, 20, 30])
print(L * 2)
print(A * 2)
print(A + 5)
Output:
[10, 20, 30, 10, 20, 30]
[20 40 60]
[15 25 35]
L * 2 repeats the list, but A * 2 multiplies every element by 2. And A + 5 adds 5 to every element โ while L + 5 would give TypeError: can only concatenate list (not "int") to list.
Analogy: Giving grace marks with a list is like the teacher walking to every desk and changing each answer sheet one by one (a loop). With a NumPy array, it is like the teacher making one announcement โ "Everyone gets +5!" โ and it happens for the whole class at once. ๐ข
"Differentiate between a Python list and a NumPy array." โ 2 marks
Answer: A list is built into Python and can store elements of different data types; its elements may not be stored together in memory, and arithmetic on all elements needs a loop. A NumPy array needs the NumPy library, stores elements of the same data type contiguously in memory, takes less memory, is faster, and supports element-wise operations such as A * 2.
8.5 ๐ ๏ธ Creating a NumPy Array from a List
The function np.array() takes a list and converts it into a NumPy array.
graph LR
L1["๐ Simple list\n[10, 20, 30]"]
F1["๐ ๏ธ np.array()"]
A1["๐งฎ 1-D array\n[10 20 30]"]
L2["๐ Nested list\n[[1, 2], [3, 4]]"]
F2["๐ ๏ธ np.array()"]
A2["๐ฒ 2-D array\n2 rows ร 2 columns"]
L1 --> F1 --> A1
L2 --> F2 --> A2
style F1 fill:#FF9800,color:#fff
style F2 fill:#FF9800,color:#fff
style A1 fill:#4CAF50,color:#fff
style A2 fill:#2196F3,color:#fff
arr = np.array( [10, 20, 30, 40] )
โโโ โโโโโโโโ โโโโโโโโโโโโโโโโ
array function a Python list
name (inside the brackets)
8.5.1 Creating a 1-D Array ๐
A 1-D (one-dimensional) array is a single row of elements, made from a simple list.
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr)
print(type(arr))
Output:
[10 20 30 40]
<class 'numpy.ndarray'>
The list can also be stored in a variable first and then passed to np.array():
import numpy as np
marks = [45, 78, 92, 60]
arr = np.array(marks)
print("List :", marks)
print("Array:", arr)
Output:
List : [45, 78, 92, 60]
Array: [45 78 92 60]
Arrays can hold strings too:
import numpy as np
subjects = np.array(["CS", "IP", "Maths"])
print(subjects)
Output:
['CS' 'IP' 'Maths']
np.array(1, 2, 3) gives a TypeError, because np.array() expects one list as its input. Write np.array([1, 2, 3]) โ the values go inside [ ].
8.5.2 All Elements Become the Same Type ๐
Because an array can hold only one data type, NumPy automatically converts all elements to a common type when the list has mixed values. This is called upcasting.
int + float
Every element becomes a float
1 becomes 1.Number + string
Every element becomes a string
5 becomes '5'bool + int
True becomes 1 and False becomes 0
True becomes 1import numpy as np
a = np.array([1, 2.5, 3])
print(a)
b = np.array([5, -7.4, "a", 7.2])
print(b)
c = np.array([True, 2, 3])
print(c)
Output:
[1. 2.5 3. ]
['5' '-7.4' 'a' '7.2']
[1 2 3]
In a, the integers 1 and 3 became floats 1. and 3. because of 2.5. In b, all the numbers became strings (shown in quotes) because of "a". In c, True became 1.
Think of the order bool โ int โ float โ string. If even one element is further along this line, all the elements are converted to that type. A single string turns the whole array into strings!
8.5.3 Choosing the Data Type โ dtype ๐๏ธ
We can also tell np.array() which data type to use with the dtype argument. The data type of an existing array is shown by arr.dtype.
import numpy as np
a = np.array([1, 2, 3], dtype=float)
print(a)
print(a.dtype)
b = np.array([1.9, 2.7, -3.5], dtype=int)
print(b)
Output:
[1. 2. 3.]
float64
[ 1 2 -3]
With dtype=int, the decimal part is simply cut off (not rounded) โ 1.9 becomes 1, and -3.5 becomes -3.
For an array of whole numbers, print(arr.dtype) shows int64 on most computers (it can be int32 on some). The number is the count of bits used to store each element.
8.5.4 Creating a 2-D Array from a Nested List ๐ฒ
A 2-D (two-dimensional) array has rows and columns, like a table. It is made from a nested list โ a list of lists, where each inner list becomes one row.
import numpy as np
table = np.array([[1, 2, 3],
[4, 5, 6]])
print(table)
Output:
[[1 2 3]
[4 5 6]]
column 0 column 1 column 2
row 0 โ 1 2 3
row 1 โ 4 5 6
Another example with mixed int and float values (upcasting applies here too):
import numpy as np
b = np.array([[2.4, 3], [4.91, 7], [0, -1]])
print(b)
Output:
[[ 2.4 3. ]
[ 4.91 7. ]
[ 0. -1. ]]
This array has 3 rows and 2 columns, and every element is a float.
np.array([[1, 2], [3]]) gives ValueError: setting an array element with a sequenceโฆ because the first row has 2 elements and the second has only 1. Every inner list must have the same number of elements.
Analogy: A 2-D array is like the seating plan of your classroom ๐ช โ rows of benches, and every row has the same number of seats. You can't have a row with 3 seats and another with only 1!
"Write Python statements to create a NumPy array from the list [5, 10, 15, 20] and display it." โ 2 marks Answer:
import numpy as np
L = [5, 10, 15, 20]
arr = np.array(L)
print(arr)
Output: [ 5 10 15 20]
8.6 ๐ป Programs on Creating Arrays
Code Example: grace_marks.py โ Array from a List of Marks
import numpy as np
marks = [45, 78, 92, 60]
arr = np.array(marks)
print("Original marks:", arr)
print("After grace :", arr + 5)
Output:
Original marks: [45 78 92 60]
After grace : [50 83 97 65]
Code Example: input_array.py โ Array from Values Typed by the User
import numpy as np
L = []
n = int(input("How many numbers? "))
for i in range(n):
L.append(int(input("Enter a number: ")))
arr = np.array(L)
print("The array is:", arr)
Sample run (the user types 3, 12, 7 and 25):
How many numbers? 3
Enter a number: 12
Enter a number: 7
Enter a number: 25
The array is: [12 7 25]
Code Example: temperatures.py โ A 2-D Array of Temperatures
import numpy as np
temps = [[31, 33, 30],
[28, 29, 27]]
arr = np.array(temps)
print("Delhi and Shimla temperatures:")
print(arr)
Output:
Delhi and Shimla temperatures:
[[31 33 30]
[28 29 27]]
Code Example: price_array.py โ Converting Prices to a Float Array
import numpy as np
price = [10, 25, 40]
arr = np.array(price, dtype=float)
print(arr)
print(arr * 1.1)
Output:
[10. 25. 40.]
[11. 27.5 44. ]
once an array exists, NumPy can describe it. arr.ndim gives the number of dimensions, arr.shape gives the size of each dimension, and arr.size gives the total number of elements. For np.array([[1, 2, 3], [4, 5, 6]]) these are 2, (2, 3) and 6. NumPy can also create arrays without a list: np.zeros(3) gives [0. 0. 0.], np.ones(4) gives [1. 1. 1. 1.] and np.arange(1, 6) gives [1 2 3 4 5]. You will use these ideas with Pandas in Class 12.
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
Using np without importing |
Python doesn't know what np is |
Write import numpy as np first |
np.array(1, 2, 3) |
Values must be passed as one list | Write np.array([1, 2, 3]) |
Expecting [1, 2.5, 3] to keep 1 and 3 as integers |
An array has only one data type | All elements become floats, so 1 prints as 1. |
Thinking np.array([5, "a"]) keeps 5 as a number |
A string makes every element a string | It becomes ['5' 'a'] |
Expecting A * 2 to repeat the array like a list |
Arithmetic on an array is element-wise | np.array([1, 2]) * 2 gives [2 4] |
Writing L + 5 for a list |
A number can't be added to a list | Convert to an array: np.array(L) + 5 |
| Rows of different lengths in a 2-D array | Every row must have the same length | Make all inner lists equal in length |
Thinking dtype=int rounds numbers |
The decimal part is cut off | 1.9 becomes 1, not 2 |
Typing pip install numpy inside Python |
pip is a command-prompt command | Run it at the command prompt / terminal |
| Printed array shows no commas, so "it's wrong" | NumPy prints arrays with spaces | [10 20 30] is the correct way an array prints |
๐ Quick Revision
- NumPy โ Numerical Python; a library for fast work on arrays of numbers
- Install โ
pip install numpy(at the command prompt); Import โimport numpy as np - Array โ elements of the same type, stored contiguously, reached by index from 0
- ndarray โ NumPy's array object (n-dimensional array)
- List vs array โ list: mixed types, more memory, needs loops; array: one type, less memory, faster, element-wise maths
- Create from a list โ
np.array([10, 20, 30])ornp.array(L) - 1-D array โ from a simple list:
[10 20 30] - 2-D array โ from a nested list; each inner list = one row; all rows the same length
- Upcasting โ bool โ int โ float โ string; one float makes all floats, one string makes all strings
- dtype โ
np.array(L, dtype=float)sets the type;arr.dtypeshows it;dtype=intcuts off decimals - Printing โ arrays print without commas:
[1 2 3]
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the full form of NumPy? Answer: Numerical Python
b) Write the statement to import NumPy with the alias np.
Answer: import numpy as np
c) Which NumPy function creates an array from a list?
Answer: np.array()
d) What is the name of NumPy's array object?
Answer: ndarray (n-dimensional array)
e) Can a NumPy array store elements of different data types? Answer: No โ all elements of an array are of the same data type
Q2: Output Based [2 marks]
import numpy as np
L = [2, 4, 6]
A = np.array(L)
print(L * 2)
print(A * 2)
Answer:
[2, 4, 6, 2, 4, 6]
[ 4 8 12]
Q3: Output Based [3 marks]
import numpy as np
p = np.array([1, 2, 3.5])
q = np.array([7, "x", 9])
r = np.array([[1, 2], [3, 4]])
print(p)
print(q)
print(r)
Answer:
[1. 2. 3.5]
['7' 'x' '9']
[[1 2]
[3 4]]
Q4: Short Answer [2 marks]
What is NumPy? Give two reasons why a NumPy array is preferred over a list for numerical data.
Answer: NumPy (Numerical Python) is a Python library used to create and work with arrays and to do fast numerical calculations. A NumPy array is preferred because (1) it takes less memory and is faster, as its elements are of the same type and stored contiguously, and (2) it supports element-wise operations, so an operation like arr + 5 works on all elements without a loop.
Q5: Program [3 marks]
Write a program to input 5 numbers into a list, convert the list into a NumPy array, and display both the list and the array.
Answer:
import numpy as np
L = []
for i in range(5):
L.append(int(input("Enter a number: ")))
arr = np.array(L)
print("List :", L)
print("Array:", arr)
Sample run (the user types 4, 8, 15, 16 and 23):
Enter a number: 4
Enter a number: 8
Enter a number: 15
Enter a number: 16
Enter a number: 23
List : [4, 8, 15, 16, 23]
Array: [ 4 8 15 16 23]
โ๏ธ Practice Problems
- What is NumPy? Why is it called a library?
- Write the command to install NumPy and the statement to import it with the alias
np. - Define an array. What does "contiguous" mean for the elements of an array?
- Write any four differences between a Python list and a NumPy array.
- Create a NumPy array from the list
[3, 6, 9, 12]and print it. - Write the output:
print(np.array([1, 2, 3]) + 10) - Write the output:
print(np.array([4, 5.5, 6]))and explain why 4 and 6 changed. - Write the output:
print(np.array([1, "two", 3])) - Create a 2-D array from the nested list
[[10, 20], [30, 40], [50, 60]]. How many rows and columns does it have? - Find the error:
arr = np.array([[1, 2, 3], [4, 5]]) - Write a program to store the prices of 4 items in a list, convert it into a float array using
dtype, and print it. - What is the difference between
L * 3for a listL = [1, 2]andA * 3for the arrayA = np.array([1, 2])? Write both outputs.