Memory layout shows how data is stored in computer memory. It helps programs access data faster.
Memory layout (C-order vs Fortran-order) in NumPy
import numpy as np # Create array with C-order (row-major) array_c = np.array([[1, 2], [3, 4]], order='C') # Create array with Fortran-order (column-major) array_f = np.array([[1, 2], [3, 4]], order='F')
order='C' means rows are stored one after another (row-major).
order='F' means columns are stored one after another (column-major).
import numpy as np # Empty array with C-order empty_c = np.empty((0, 3), order='C') print(empty_c) print(empty_c.flags['C_CONTIGUOUS'])
import numpy as np # Single element array with Fortran-order single_f = np.array([42], order='F') print(single_f) print(single_f.flags['F_CONTIGUOUS'])
import numpy as np # Array with C-order array_c = np.array([[1, 2], [3, 4]], order='C') print(array_c.flags['C_CONTIGUOUS']) print(array_c.flags['F_CONTIGUOUS'])
import numpy as np # Array with Fortran-order array_f = np.array([[1, 2], [3, 4]], order='F') print(array_f.flags['F_CONTIGUOUS']) print(array_f.flags['C_CONTIGUOUS'])
This program creates the same 2x3 array twice: once with C-order and once with Fortran-order. It prints the arrays and shows which memory layout they use.
import numpy as np # Create a 2x3 array in C-order array_c = np.array([[10, 20, 30], [40, 50, 60]], order='C') print("Array in C-order:") print(array_c) print("Is C contiguous?", array_c.flags['C_CONTIGUOUS']) print("Is Fortran contiguous?", array_c.flags['F_CONTIGUOUS']) # Create the same array in Fortran-order array_f = np.array([[10, 20, 30], [40, 50, 60]], order='F') print("\nArray in Fortran-order:") print(array_f) print("Is C contiguous?", array_f.flags['C_CONTIGUOUS']) print("Is Fortran contiguous?", array_f.flags['F_CONTIGUOUS'])
Time complexity: Memory layout does not affect time to create arrays but affects speed of some operations.
Space complexity: Both layouts use the same amount of memory.
Common mistake: Assuming all numpy arrays are C-contiguous by default.
Use C-order when you process data row by row, Fortran-order when processing column by column.
Memory layout controls how array data is stored in memory.
C-order stores rows one after another; Fortran-order stores columns one after another.
Choosing the right layout can improve speed and compatibility.