Python Arrays 🗃️
Arrays vs Lists
Python does not have built-in support for Arrays, but Python Lists can be used instead.
However, Python does have a built-in module called array for arrays of a specific type, and the popular NumPy library is the standard for working with arrays in Data Science.
🥚 Analogy: The Egg Carton
Think of a standard Python List as a shopping bag: you can throw anything in it (apples, milk, bread).
Think of an Array (especially NumPy) as an egg carton:
- It has a fixed structure.
- It's designed to hold only one type of thing (eggs).
- Because it's specialized, it's much safer and easier to stack/transport (Performance).
✨ Using Lists as Arrays
For most general programming tasks, Python Lists are used where arrays would be used in other languages.
cars = ["Ford", "Volvo", "BMW"]
# Accessing
x = cars[0]
# Modifying
cars[0] = "Toyota"
# Length
print(len(cars)) # 3📦 The array Module
Python has a built-in module called array that can be used to create arrays of a specific type (like integers only). This is more memory efficient than lists for large amounts of data.
import array as arr
# 'i' represents signed integer
a = arr.array('i', [1, 2, 3])
print(a[0]) # 1
a.append(4)
print(a) # array('i', [1, 2, 3, 4])🚀 NumPy Arrays
For data science and heavy mathematics, NumPy arrays are the industry standard. They are much faster than Python lists.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr)) # <class 'numpy.ndarray'>🎯 Real-World Application: Image Processing
Did you know that digital images are just giant arrays of numbers?
A grayscale image is a 2D array where each number represents the brightness of a pixel (0=Black, 255=White).
import numpy as np
# Create a tiny 3x3 image (black and white pixels)
image = np.array([
[0, 255, 0],
[255, 0, 255],
[0, 255, 0]
])
print("Pixel at row 1, col 1:", image[1, 1]) # 0 (Black)⚠️ Key Difference
- Lists: Can contain different data types, built-in.
- Arrays (module): Must contain same data type, built-in module.
- NumPy Arrays: Must contain same data type, external library (fastest).