Junior — Middle
Is it possible to detect the presence of an array in Python code?
sobes.tech AI
Answer from AI
In Python, there is no built-in 'array' type like in other languages, but there are several ways to determine the presence of an array or a similar structure:
-
Lists (
list) — the most common type for storing sequences. -
Arrays from the
arraymodule — more compact, but with a restriction on element types. -
NumPy arrays (
numpy.ndarray) — used in scientific computing.
To determine if an object is an array, you can check its type or use isinstance:
import array
import numpy as np
def is_array(obj):
return isinstance(obj, (list, array.array, np.ndarray))
print(is_array([1, 2, 3])) # True
print(is_array(array.array('i', [1,2,3]))) # True
print(is_array(np.array([1,2,3]))) # True
print(is_array("string")) # False
Thus, to check for an "array" in Python, you need to specify which data type is considered.