Python NumPy - Check two arrays have the same contiguous memory layout

By IncludeHelp Last updated : September 14, 2024

Contiguous memory layout is the memory locations where each element of an array is stored are consecutive and sequential, with no gaps between them. Here, we will check if two arrays have the same contiguous memory layout or not.

Checking if two arrays have the same contiguous memory layout or not

To check if check two arrays have the same contiguous memory layout or not, we can use numpy.ascontiguousarray() to create contiguous copies of the two input arrays, and then compares their memory layout by checking their __array_interface__ property.

Basically, it compares the memory address of the first element in each array to determine whether they are stored contiguously in memory. If the memory addresses are the same, then the function returns True, indicating that the two arrays have the same contiguous memory layout. Otherwise, it returns False.

Python code to check if two arrays have the same contiguous memory layout or not

Let us understand with the help of an example:

# Importing numpy
import numpy as np

# Creating two arrays
arr1 = np.array([6, 4, 56, 4, 2, 6])
arr2 = np.array([6, 4, 56, 4, 2, 6])

# Display original arrays
print("Original array 1", arr1, "\n")
print("Original array 2", arr2, "\n")

# Defining a function
def fun(arr1, arr2):
    # Checking that both arrays have contiguous memory layout
    arr1_ = np.ascontiguousarray(arr1)
    arr2_ = np.ascontiguousarray(arr2)

    # Compare the memory layout of the two arrays
    layout = (
        arr1_.__array_interface__["data"][0] == arr2_.__array_interface__["data"][0]
    )

    return layout

# Display result
print("Do both arrays have same contiguous memory layout :\n", fun(arr1, arr2), "\n")

Output

Original array 1 [ 6  4 56  4  2  6] 

Original array 2 [ 6  4 56  4  2  6] 

Do both arrays have same contiguous memory layout :
 False 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.