Contiguous arrays store data in a continuous block of memory. This helps programs run faster. Stride tricks let you view the same data in different shapes without copying it.
Contiguous arrays and stride tricks in NumPy
import numpy as np # Creating a contiguous array array = np.array([1, 2, 3, 4, 5]) # Checking if array is contiguous is_contiguous = array.flags['C_CONTIGUOUS'] # Using stride tricks to create a sliding window view from numpy.lib.stride_tricks import sliding_window_view windowed_array = sliding_window_view(array, window_shape=3)
Contiguous means data is stored in one continuous block in memory.
Stride tricks create new views without copying data, so changes affect the original array.
import numpy as np # Empty array empty_array = np.array([]) print(empty_array.flags['C_CONTIGUOUS'])
import numpy as np # One element array one_element_array = np.array([10]) print(one_element_array.flags['C_CONTIGUOUS'])
import numpy as np # Non-contiguous array by slicing array = np.array([1, 2, 3, 4, 5]) sliced_array = array[::2] print(sliced_array.flags['C_CONTIGUOUS'])
import numpy as np from numpy.lib.stride_tricks import sliding_window_view array = np.array([1, 2, 3, 4, 5]) windowed = sliding_window_view(array, 2) print(windowed)
This program shows how to check if arrays are contiguous, how slicing can create non-contiguous arrays, and how stride tricks create sliding windows without copying data. It also shows that modifying the window view changes the original array.
import numpy as np from numpy.lib.stride_tricks import sliding_window_view # Create a 1D numpy array original_array = np.array([10, 20, 30, 40, 50]) # Check if the array is contiguous print(f"Is original array contiguous? {original_array.flags['C_CONTIGUOUS']}") # Create a sliced array with step 2 (non-contiguous) sliced_array = original_array[::2] print(f"Sliced array: {sliced_array}") print(f"Is sliced array contiguous? {sliced_array.flags['C_CONTIGUOUS']}") # Use stride tricks to create sliding windows of size 3 windows = sliding_window_view(original_array, window_shape=3) print(f"Sliding windows (size 3):\n{windows}") # Modify a value in the sliding window view windows[0, 0] = 999 print(f"Modified original array after changing window view:\n{original_array}")
Time complexity: Checking contiguity is O(1). Creating sliding windows is O(1) because it creates views, not copies.
Space complexity: Sliding windows use no extra space for data, only for metadata.
Common mistake: Assuming sliced arrays are always contiguous. Slicing with steps often creates non-contiguous arrays.
Use stride tricks when you want efficient views without copying data. Use copying if you need independent arrays.
Contiguous arrays store data in one continuous block for fast access.
Stride tricks create new views with different shapes without copying data.
Modifying views created by stride tricks changes the original array.