2025-09-17
Let’s see the standard way to handle this.
import time
# Create a large list of integers
my_list = list(range(10000000))
# Time the operation
start_time = time.time()
# Square each element using a list comprehension
squared_list = [x**2 for x in my_list]
list_time = time.time() - start_time
print(f"List comprehension time: {list_time:.4f} seconds")for loop is an interpreted operation.ndarray (n-dimensional array).import numpy as np
# Create an array from a Python list
my_np_array = np.array([1, 2, 3, 4, 5])
print(f"Array: {my_np_array}")
print(f"Type: {type(my_np_array)}")
print(f"Data type: {my_np_array.dtype}") # Notice the single data type
# NumPy forces homogeneity - it will upcast types
hetero_list = [1, 2, 3.5, 4]
hetero_array = np.array(hetero_list)
print(f"Upcast array: {hetero_array}")
print(f"Data type: {hetero_array.dtype}")import numpy as np
import time
# Create a large NumPy array
large_np_array = np.arange(10000000)
# Time the NumPy operation
start_time = time.time()
# Perform the vectorized operation
squared_np_array = large_np_array**2
np_time = time.time() - start_time
print(f"NumPy vectorization time: {np_time:.4f} seconds")
# Compare with our previous result
# List time was ~ 2.0 seconds
print("NumPy is orders of magnitude faster!")import numpy as np
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f"Original Array: {data}")
print(f"Sum of elements: {np.sum(data)}")
print(f"Mean of elements: {np.mean(data)}")
print(f"Standard deviation: {np.std(data)}")
print(f"Maximum value: {np.max(data)}")
# Or for a 2D array (matrix)
matrix = np.array([[1, 2], [3, 4]])
print(f"Sum of each column: {np.sum(matrix, axis=0)}")append() and pop() methods might be more efficient for those specific tasks.| Feature | Python List | NumPy Array |
|---|---|---|
| Data Type | Heterogeneous (mixed) | Homogeneous (uniform) |
| Size | Dynamic (can grow/shrink) | Fixed (expensive to resize) |
| Memory | High (stores pointers) | Low (stores raw data) |
| Speed | Slower (interpreted loop) | Faster (vectorized, compiled code) |
| Best For | General-purpose data, collections of mixed types | Large-scale numerical computation, linear algebra |
Let’s put your new knowledge to the test.
Write a short Python program that:
np.zeros().