Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'array' is not defined" occurs when we use the
array
module without importing it first. To solve the error, import from the
array
module before using it - from array import array
. If using numpy
,
access array
on the numpy
module, e.g. np.array
.
Here is an example of how the error occurs.
# ⛔️ NameError: name 'array' is not defined arr = array('l', [1, 2, 3]) print(arr)
To solve the error, we have to import the array
class from the
array module.
# ✅ import array class from array module first from array import array arr = array('l', [1, 2, 3]) print(arr)
If you use the numpy
module, access array
on the module after importing it.
# ✅ import numpy import numpy as np # 👇️ access array on np module arr = np.array([1, 2, 3]) print(arr)
Even though the array
module is in the Python standard library, we still have
to import it before using it.
a
when importing array
because module names are case-sensitive.Also, make sure you haven't imported array
in a nested scope, e.g. a function.
Import the module at the top level to be able to use it throughout your code.
The array
module defines an object type which can compactly represent an array
of values.
If you don't need to constrain the type of objects stored in a sequence, use a Python list instead.
my_list = [1, 2, 3] print(my_list)
You can read more about the array
module by visiting the
official docs.