Contents
What is NumPy..............................................................................................................................................3
Why Numpy is Important..............................................................................................................................3
What is Array.................................................................................................................................................3
Dimensions in Array......................................................................................................................................3
Numpy VS Python list...................................................................................................................................4
Installation of NumPy....................................................................................................................................4
Import Numpy................................................................................................................................................4
Creating Array................................................................................................................................................5
Get array from user as input......................................................................................................................5
Dimensions in array.......................................................................................................................................6
Pro-Tip to Remember:...........................................................................................................................6
Creating array with random numbers............................................................................................................7
Array Slicing in NumPy.................................................................................................................................8
Real-Life Example.........................................................................................................................................8
2D Array Slicing......................................................................................................................................10
Fancy Indexing (Advanced)....................................................................................................................11
Master NumPy: Creating Arrays with Functions...................................................................................12
2. [Link]() — The Pre-Filled Template.................................................................................................12
3. [Link]() — The Number Sequencer...............................................................................................13
4. [Link]() — The Equal Divider.....................................................................................................13
Quick Memory Cheat Sheet....................................................................................................................15
Ultimate NumPy Cheat Sheet: Understanding Data Types...................................................................16
Arithmetic Operations..................................................................................................................................18
NumPy Functions for Arithmetic Operations..............................................................................................19
What is NumPy
NumPy stands for Numerical Python. It is the foundational Python library used for working with large
sets of numbers efficiently. Think of it as Python on rocket fuel for handling math data.
Real-Life Example: Imagine you are a school principal looking at a massive spreadsheet
containing the grades of 10,000 students. NumPy is the super-calculator that lets you analyze all
those grades at once.
Why Numpy is Important
Python lists are great, but they get incredibly slow when dealing with millions of items. NumPy is critical
because it is written in C under the hood, making it scary fast and highly memory-efficient for data
crunching.
Real-Life Example: Imagine moving 100 bricks one by one using a bicycle (Python List) versus
moving all 100 bricks at once in a massive dump truck (NumPy).
What is Array
An array is a central data structure of NumPy. It is a grid of values, usually numbers, where every single
item must be of the exact same data type (e.g., all integers or all floats).
Real-Life Example: An egg carton. Every slot is exactly the same size, organized in a perfect
grid, and holds the exact same type of item (eggs).
Dimensions in Array
Dimensions are the "layers" or directions of your data grid.
0-D: A single number (Scalar).
1-D: A single row of numbers (Vector).
2-D: A table with rows and columns (Matrix).
3-D: A stack of tables (like a book of matrices).
Real-Life Example:
o 1-D: A single shopping list.
o 2-D: A monthly calendar (rows are weeks, columns are days).
o 3-D: A year's worth of calendars stacked on top of each other.
Numpy VS Python list
Python lists are flexible jack-of-all-trades (can hold text, numbers, and objects together), while NumPy
arrays are specialized specialists (only hold one type of data but process it at lightning speed).
Quick Comparison Table
Feature Python List NumPy Array
Data Type Can hold mixed types (strings + integers) Must be all the same type
Feature Python List NumPy Array
Speed Slower for large datasets Blazing fast (optimized C code)
Memory Uses more memory per item Extremely compact
Operations list * 2 repeats the list array * 2 multiplies every number by 2
Installation of NumPy
Because NumPy doesn't come built-in with Python, you have to download it using Python’s package
installer (pip) via your computer's terminal or command prompt.
Real-Life Example: Buying an add-on pack or DLC for a video game you already own to get
cool new features.
Code Command:
# Run this in your Terminal or Command Prompt (Not inside Python)
o pip install numpy
Import Numpy
To actually use NumPy in your Python script, you must tell Python to bring it into the file. By universal
convention, programmers alias it as np to save time typing.
Real-Life Example: Calling a specialist by their nickname. Instead of yelling "Hey
Numerical Python!", you just shout "Hey NP!".
Code Command:
Creating Array
In Python, we have lists. In NumPy, we have arrays. An array is a grid of values, usually all of the same
type. Think of it as a highly organized egg carton where every slot is perfectly uniform, making it
incredibly fast for your computer to process.
Real-Life Example: Imagine a row of identical lockers in a school hallway. Each locker holds
one student's backpack.
Key Function: [Link]()
Code Example
Get array from user as input
Sometimes you don't know the data beforehand—you need to ask the user for it. Because NumPy doesn't
have a direct input() function, we capture the user's input as a standard Python list or string first, and then
convert that list into a high-speed NumPy array.
Real-Life Example: A waiter writing down a table's custom drink orders on a notepad (user
input), and then handing that list to the bartender who inputs it into the digital kitchen system
(NumPy array) for fast processing.
Key Trick: Use a Python list comprehension or split(), then wrap it in [Link]().
Code Example
Dimensions in array
Dimensions are just the "layers" of your data.
0-D (Scalar): A single number. (A single dot).
1-D (Vector): A single row of numbers. (A straight line/list).
2-D (Matrix): A grid with rows and columns. (A spreadsheet or a table).
3-D: A stack of grids. (An entire Excel workbook with multiple sheets).
Real-Life Example:
o 1-D: A single row of houses on a street.
o 2-D: A multi-story apartment building (Floors $\times$ Rooms).
Key Property: .ndim (tells you how many dimensions your array has).
Code Example
Pro-Tip to Remember:
Count the number of opening square brackets [ at the very beginning of your array definition.
[ = 1D
[[ = 2D
[[[ = 3D
Creating array with random numbers
Imagine you have a magical bag of numbers, and every time you reach in, you pull out a completely
unpredictable number. In NumPy, Random Number Generation is like using that magical bag to
instantly fill up an entire grid (array) with random data.
Instead of typing out numbers manually, you let Python roll the dice for you. This is incredibly useful for
simulating real-world chaos, testing your code, or setting up games.
Code Examples
Random Decimals between 0 and 1
Random numbers close to Zero (randn)
o It either generate +ve or -ve numbers.
Random Integers (Whole Numbers)
o Use [Link]() when you need whole numbers within a specific range (like
rolling a dice).
o
Array Slicing in NumPy
Array slicing in NumPy means selecting a specific portion of an array using indexes.
It helps us quickly extract needed data without copying the whole array.
Simple Formula
start → where slicing begins
stop → where slicing ends (not included)
step → jump between values
Real-Life Example
Imagine a pizza cut into 8 slices.
If you only want slices 2 to 5, you don’t take the whole pizza — you take only the required part.
Array slicing works the same way:
You pick only the needed data from an array.
Code Example
2D Array Slicing
Fancy Indexing (Advanced)
Selecting elements using lists of indexes.
Trick Meaning
: everything
every 2nd
::2
element
[::-1] reverse
-1 last element
conditional
arr > 10
filtering
[rows, columns] 2D slicing
Master NumPy: Creating Arrays with Functions
When working with data in Python, typing out lists manually is tedious. NumPy provides built-in
functions to automatically generate arrays of any size, pre-filled with zeros, ones, random numbers, or
sequences.
Think of these functions like a factory assembly line: you tell the machine the shape and the type of
product you want, and it instantly spits it out for you.
1. [Link]() — The Blank Slate
Creates an array filled entirely with zeros.
Real-Life Example: Imagine you are a teacher preparing a digital grade book for a new semester.
Before the exams happen, every student's score is initialized to 0.
Syntax & Code:
2. [Link]() — The Pre-Filled Template
Creates an array filled entirely with ones.
Real-Life Example: You are setting up an online RSVP system for a wedding. By default,
you assume every invited guest is bringing exactly 1 plus-one until they update their
response.
Syntax & Code:
3. [Link]() — The Number Sequencer
Generates an array with a sequence of numbers, defining a start, stop, and step size (just like Python's
built-in range(), but much faster).
Real-Life Example: A gym coach wants to set up cones on a track field starting at meter 0,
ending before meter 20, spaced out every 5 meters.
Syntax & Code:
4. [Link]() — The Equal Divider
Short for "Linear Space". You tell it where to start, where to end, and how many total pieces you want. It
mathematically calculates the exact spacing for you.
Real-Life Example: You have an 8-foot-long wooden plank and you need to make exactly 5
evenly spaced pencil marks to cut it into equal sections.
Syntax & Code:
Quick Memory Cheat Sheet
Function What it does Best Remembered As...
[Link](size) Fills everything with 0. Resetting a scoreboard.
[Link](size) Fills everything with 1. Setting default quantities.
Counts up by a specific step Walking up stairs 2 steps at a
[Link](start, stop, step)
size. time.
[Link](start, stop, Divides a range into equal
Slicing a pizza into equal slices.
num) chunks.
Ultimate NumPy Cheat Sheet: Understanding Data Types
In standard Python, lists can hold a mix of anything (integers, strings, floats), which makes them flexible
but slow. NumPy arrays are like a disciplined military squad: everyone must wear the exact same
uniform. This uniformity is why NumPy is blindingly fast.
Every element in a NumPy array has a specific DataType (dtype) that dictates exactly how much
memory it takes up and how the computer interprets it.
1. Integers (Whole Numbers)
What it is: Used for whole numbers without decimals (positive, negative, or zero).
Real-Life Example: Counting the number of students in a classroom, counting cars in a
parking lot, or tracking website page views. You can't have 2.5 cars!
NumPy Types: np.int32 or np.int64 (the numbers represent how many "bits" of memory it
uses).
2. Floats (Floating-Point Numbers)
What it is: Used for numbers with fractional parts or decimal points.
Real-Life Example: Tracking body temperature ($98.6^\circ\text{F}$), measuring GPS
coordinates, or checking stock prices ($150.75).
NumPy Types: np.float32 or np.float64.
3. Booleans (True / False)
What it is: A binary type that can only hold two values: True or False. It is the ultimate "yes
or no" data type.
Real-Life Example: Passing or failing an exam, checking if a store is open or closed, or
tracking if a user is logged in.
NumPy Type: np.bool_.
4. Strings (Text Data)
What it is: Used to store text, letters, or words. In NumPy, strings have a fixed maximum
length to keep processing speeds ultra-fast.
Real-Life Example: A list of city names, product categories on Amazon, or a lineup of
patient names.
NumPy Type: np.str_ (often shows up as <U meaning Unicode).
Quick Memory Trick
Think of NumPy dtypes as Tupperware containers.
If you pick an Integer container, you can only fit whole blocks.
If you pick a Float container, it pours in smoothly like water.
If you pick a Boolean container, it only has a light switch that is either On or Off.
Matching the right container to your data saves massive amounts of computer memory!
Arithmetic Operations
Arithmetic Operations in NumPy are mathematical calculations performed on array elements, such as
addition (+), subtraction (-), multiplication (*), division (/), and power ()**. NumPy applies these
operations element by element, making calculations fast and easy.
Real-Life Example
Imagine you own two grocery stores. You want to find the total number of items sold each day by
combining sales from both stores. NumPy can add the daily sales of both stores instantly.
Code Example
Other Arithmetic Operations
NumPy Functions for Arithmetic Operations
NumPy provides built-in functions to perform arithmetic operations on arrays. These functions work
element by element and make calculations faster and more readable.
Real-Life Example
Suppose a shop records sales from two branches. Instead of calculating totals manually, NumPy functions
can quickly perform the calculations on all sales data at once.
1. Addition — [Link]()
Adds corresponding elements of two arrays.
2. Subtraction — [Link]()
Subtracts elements of one array from another.
3. Multiplication — [Link]()
Multiplies corresponding elements.
4. Division — [Link]()
Divides corresponding elements.
5. Power — [Link]()
Raises elements to a specified power.
6. Modulus (Remainder) — [Link]()
Returns the remainder after division.
7. Absolute Value — [Link]()
Converts negative values to positive.
Function Purpose
[Link]() Addition
[Link]() Subtraction
[Link]() Multiplication
[Link]() Division
[Link]() Power/Exponent
[Link]() Remainder
[Link]() Absolute Value