Vectorisation vs Loops

Python · NumPy Library

Theory

Vectorisation means writing an operation for the whole array, such as total = price * qty, instead of looping over elements in Python. The loop version runs the Python interpreter once per element, checking types every time. The vectorised version hands the whole array to NumPy's compiled code, which loops in C over values packed in memory, so it is often 10 to 100 times faster on large arrays.

Most loops can be replaced: element-wise maths with operators and ufuncs, if-else with np.where, filters with boolean masks, and running totals with np.cumsum. Vectorised code is usually shorter and closer to the maths too. The trade-off is memory, because each step creates a temporary array; for very large data, work in chunks. A loop is still fine for small lists or logic that depends on the previous result.

Why we use it

Data pipelines touch millions of values. Replacing Python loops with array operations turns minutes into seconds and also makes the code shorter and easier to read.

When to use it

Reach for vectorised operations whenever you loop over numbers in an array or DataFrame column. Keep a plain loop for small data, complex step-by-step logic, or calls to functions that cannot take arrays.

How it works

  1. Python loop over array elements
  2. Is each step independent of the previous result? Yes: Rewrite with operators, ufuncs, np.where or masks. No: Keep the loop or use np.cumsum style helpers.
  3. Check the vectorised result equals the loop result
  4. Time both versions on realistic data
  5. Faster, shorter code

Syntax

# loop
out = [p * q for p, q in zip(price, qty)]
# vectorised
out = price * qty
np.where(cond, a, b)  np.cumsum(a)

Example

price = np.arange(1, 1_000_001)
total = price * 1.18    # one line, no loop

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic