← Back to NumPy Course | Chapter 1: Getting Started | Lesson 4 of 7

Why NumPy over lists

A Python list can hold anything but is slow at maths; a NumPy array holds one kind of number and does maths on everything at once.

In this page:

  1. Why NumPy over lists

Why NumPy over lists

Python lists store pointers to full Python objects, so arithmetic needs a slow loop. NumPy arrays store raw numbers in one contiguous block of memory and apply operations in compiled code. That means less memory, faster maths and much shorter code.

Note: Multiplying a list by 2 repeats it; multiplying an array by 2 doubles every element.

Example: Why NumPy over lists

python
import numpy as np

nums = [1, 2, 3]
arr = np.array(nums)

print("list * 2  :", nums * 2)
print("array * 2 :", arr * 2)
print("list + list:", nums + nums)
print("array + array:", arr + arr)

# Output:
# list * 2  : [1, 2, 3, 1, 2, 3]
# array * 2 : [2 4 6]
# list + list: [1, 2, 3, 1, 2, 3]
# array + array: [2 4 6]
Related Topics
Common Mistakes
  1. Expecting list * 2 to double the values
  2. Mixing types and being surprised by automatic conversion
  3. Using lists for large numeric datasets
Chapter Summary
  • Arrays use contiguous typed memory
  • Operators work element-wise on arrays
  • Arrays use far less memory than lists
  • Code is shorter with no explicit loops
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.