Back to Python Notes
Topic #250

Searching and Sorting Arrays

Learn how to efficiently find specific values and order data within Python lists using built-in methods and the NumPy library.

What it is

Searching involves locating a specific element or its position within a collection, while sorting arranges elements in a defined order (ascending or descending). In standard Python, lists provide basic methods for these tasks. For large datasets or numerical arrays, the NumPy library offers highly optimized functions that operate on contiguous memory blocks, significantly outperforming native list operations.

Key terms include index (the position of an element), sort order, and stability (whether equal elements retain their original relative order).

Why it matters

  • Data Analysis: Sorting allows you to quickly identify outliers, top performers, or trends by ordering values.
  • Efficient Lookup: Searching sorted data enables binary search algorithms, reducing lookup time from linear O(n) to logarithmic O(log n).
  • Preprocessing: Many machine learning models require input features to be normalized or ordered before training.
  • User Experience: Applications often need to display results in a meaningful order, such as alphabetical names or chronological dates.

Syntax or steps

For standard Python lists, use .sort() to modify the list in place or sorted() to return a new list. Use .index(value) to find the first occurrence of a value.

For NumPy arrays, use np.sort(array) to return a sorted copy and np.argmax(array) to find the index of the maximum value. Note that np.sort does not sort in place; it returns a new array.

Example

import numpy as np

# Standard Python List
data_list = [45, 12, 78, 3, 90]
print("Original:", data_list)

# Sort in place
data_list.sort()
print("Sorted List:", data_list)

# Find index of value 78
try:
    idx = data_list.index(78)
    print(f"Index of 78: {idx}")
except ValueError:
    print("Value not found")

# NumPy Array Operations
arr = np.array([45, 12, 78, 3, 90])

# Return sorted copy
sorted_arr = np.sort(arr)
print("Sorted NumPy:", sorted_arr)

# Index of maximum value
max_idx = np.argmax(arr)
print(f"Index of max value ({arr[max_idx]}): {max_idx}")

This code demonstrates two approaches. First, it sorts a standard list and finds an element's index. Second, it uses NumPy to create a sorted version of an array without modifying the original, then identifies the position of the largest number using argmax.

Common mistakes

  • Confusing .sort() and sorted(): .sort() modifies the original list and returns None. Assigning x = my_list.sort() will set x to None. Use sorted(my_list) if you need a new list.
  • Assuming np.sort is in-place: Unlike Python lists, np.sort returns a new array. To sort in place with NumPy, use arr.sort().
  • Ignoring mixed types: Sorting lists containing both strings and integers raises a TypeError in Python 3. Ensure all elements are comparable.
  • Using index() on unsorted data for performance: If you need to search frequently, sort the data first and use binary search logic, rather than scanning the list repeatedly.

When to use it

ScenarioRecommended ToolReason
Small lists (< 100 items)Python Lists (.sort())Simplicity and no external dependencies.
Large numerical arraysNumPy (np.sort)Significantly faster due to C-level optimization.
Need original order preservedsorted() or np.sort()Returns a new object, leaving the source unchanged.
Memory constrainedIn-place sort (.sort() or arr.sort())Does not allocate memory for a duplicate structure.

Practice

Guided Exercise: Create a list of student scores: [88, 92, 76, 92, 85]. Sort it in ascending order and print the index of the first score above 90.

Challenge: Using NumPy, create an array of random integers between 1 and 100. Find the index of the minimum value and the index of the maximum value.

Hint: For the challenge, look up np.argmin() alongside np.argmax().

Quick check

Question: What is the output of print([3, 1, 2].sort())?

Answer: None. The .sort() method modifies the list in place and returns nothing.

Summary

Python provides flexible tools for searching and sorting, ranging from simple list methods to high-performance NumPy functions. Choose in-place sorting for memory efficiency and copies for preserving original data, always considering the size and type of your dataset.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Searching and Sorting Arrays – FAQs

Quick answers about learning Searching and Sorting Arrays in Python.

This free note from Coding Now Tech Institute explains Searching and Sorting Arrays in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Searching and Sorting Arrays, is 100% free with no signup required.
With focused practice, most students grasp Searching and Sorting Arrays in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now