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?
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?
You need to import the array method from the module.
from array import array
array in Python isn't exactly like an array in languages like C or Java, they are constrained and you must specify a type that the array will hold. You can use lists like you would arrays in other languages, but otherwise, you have to specify that your array holds integers. Check out the first part of the doc: docs.python.org/library/array.htmlFor 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.
array([1, 2, 3]), however you have to input them as np.array([1, 2, 3]). (After importing import numpy as np.)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]
a = [b for i in range(10)] That will create a new list [b,b,b,b,b,b,b,b,b,b]a = []; a.append(1); a.append(2); a now has the value [1,2]. You can also access individual elements using index notation: print a[1], a[1] = 3, or slice notation print a[:2] -- prints the first two elements of a.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.
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
**from array import *** myarray=array('i',[10,39,48,38])
Maybe you haven´t executed the cell. It worked for me