NameError: name 'array' is not defined in python

Question:

I get NameError: name 'array' is not defined in python error when I want to create array, for example:

a = array([1,8,3])

What am I doing wrong? How to use arrays?

Asked By: Templar

||

Answers:

You need to import the array method from the module.

from array import array

http://docs.python.org/library/array.html

Answered By: wkl

You probably don’t want an array. Try using a list:

a = [1,8,3]

Python lists perform like dynamic arrays in many other languages.

Answered By: Russell Borogove

If you need a container to hold a bunch of things, then lists might be your best bet:

a = [1,8,3]

Type

dir([])

from a Python interpreter to see the methods that lists support, such as append, pop, reverse, and sort.
Lists also support list comprehensions and Python’s iterable interface:

for x in a:
    print x

y = [x ** 2 for x in a]
Answered By: Matt Fenwick

For basic Python, you should just use a list (as others have already noted).

If you are trying to use NumPy and you want a NumPy array:

import numpy as np

a = np.array([1,8,3])

If you don’t know what NumPy is, you probably just want the list.

Answered By: steveha

You need to import the array.

from numpy import array
Answered By: Hashem Moradmand

In python Import problem occurs when you accidentally name your working file the same as the module name. This way the python opens the same file you created using the same as module name which causes a circular loop and eventually throws an error.

This question is asked 10 yrs ago , but it may be helpful for late python learners

Answered By: Debankan

If you’re trying to use NumPy, use this:

import numpy as np
a = np.array([1, 2, 3])

If not then a list is way more easier:

a = [1, 2, 3]
Answered By: Jesimiel Almedejar

**from array import ***
myarray=array(‘i’,[10,39,48,38])

Answered By: Amal Salilan

Maybe you havenĀ“t executed the cell. It worked for me

enter image description here

Answered By: Carlos Fernando
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.