Fix - NameError: name 'array' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

Fix - NameError: name 'array' is not defined in Python #

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.

nameerror name array is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ 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.

main.py
# ✅ 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.

main.py
# ✅ 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.

Make sure you haven't used a capital letter 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.

Arrays are very similar to lists, except that the type of objects stored in them is constrained, e.g. strings, integers or floating point numbers.

If you don't need to constrain the type of objects stored in a sequence, use a Python list instead.

main.py
my_list = [1, 2, 3] print(my_list)

You can read more about the array module by visiting the official docs.

Use the search field on my Home Page to filter through my more than 1,000 articles.