Sorting and Searching

Python · NumPy Library

Theory

np.sort(arr) returns a sorted copy in ascending order, and arr.sort() sorts in place; for descending order reverse it with [::-1]. np.argsort(arr) returns the positions that would sort the array, which lets you reorder a second array the same way, for example names[np.argsort(-scores)] gives names from highest to lowest score.

np.where(cond) returns the positions where a condition is True, and np.where(cond, a, b) builds a new array taking a where True and b where False, like a vectorised if-else. np.unique(arr, return_counts=True) gives the distinct values in sorted order with how often each appears. np.searchsorted(sorted_arr, value) finds where a value would be inserted to keep the order, which is handy for putting amounts into slabs or bins.

Why we use it

Ranking, finding the top items, counting categories and labelling values are everyday tasks. These functions do them on whole arrays without loops, and argsort keeps related arrays aligned when you reorder.

When to use it

Use argsort to rank or to sort several arrays together, np.where for if-else labels, unique with counts for frequency tables and searchsorted for bucketing into sorted thresholds. For labelled data, pandas sort_values and value_counts read better.

How it works

  1. Array to organise
  2. Need the values in order? Yes: np.sort (copy) or arr.sort() (in place). No: Keep going.
  3. Need to reorder another array the same way? Yes: order = np.argsort(a); other[order]. No: Keep going.
  4. Need an if-else label per value? Yes: np.where(cond, a, b). No: Keep going.
  5. Count categories with np.unique(a, return_counts=True)
  6. Sorted, ranked, labelled or counted result

Syntax

np.sort(a)  a.sort()  np.sort(a)[::-1]
np.argsort(a)
np.where(cond)  np.where(cond, x, y)
np.unique(a, return_counts=True)
np.searchsorted(sorted_a, v)

Example

scores = np.array([72, 95, 64])
print(np.argsort(scores))                  # [2 0 1]
print(np.where(scores >= 70, 'Pass', 'Fail'))

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