133

Is possible to construct a NumPy array from a python list?

yatu
  • 80,714
  • 11
  • 64
  • 111
Hossein
  • 37,539
  • 55
  • 135
  • 174

9 Answers9

169

First of all, I'd recommend you to go through NumPy's Quickstart tutorial, which will probably help with these basic questions.

You can directly create an array from a list as:

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

Or from a from a nested list in the same way:

import numpy as np
a = np.array( [[2,3,4], [3,4,5]] )
yatu
  • 80,714
  • 11
  • 64
  • 111
Bryce Siedschlaw
  • 4,016
  • 1
  • 23
  • 34
  • 21
    import numpy as np; and add np. before array(np.array([]); for someone who might be confused – Abhi Sep 04 '16 at 21:33
  • 3
    I would have put that syntax a little differently. How about `import numpy as np` then `a = np.array ( [[2,3,4],[3,4,5]] )` ? – SDsolar Sep 12 '17 at 23:12
42

you mean something like this ?

from numpy  import array
a = array( your_list )
Cédric Julien
  • 74,806
  • 15
  • 120
  • 127
19

Yes it is:

a = numpy.array([1,2,3])
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
16

You want to save it as a file?

import numpy as np

myList = [1, 2, 3]

np.array(myList).dump(open('array.npy', 'wb'))

... and then read:

myArray = np.load(open('array.npy', 'rb'))
eumiro
  • 194,053
  • 32
  • 286
  • 259
8

You can use numpy.asarray, for example to convert a list into an array:

>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
Bilal
  • 2,296
  • 5
  • 32
  • 55
4

I suppose, you mean converting a list into a numpy array? Then,

import numpy as np

# b is some list, then ...    
a = np.array(b).reshape(lengthDim0, lengthDim1);

gives you a as an array of list b in the shape given in reshape.

Hadamard
  • 51
  • 3
0

Here is a more complete example:

import csv
import numpy as np

with open('filename','rb') as csvfile:
     cdl = list( csv.reader(csvfile,delimiter='\t'))
     print "Number of records = " + str(len(cdl))

#then later

npcdl = np.array(cdl)

Hope this helps!!

SDsolar
  • 2,109
  • 2
  • 20
  • 31
0
import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

0

maybe:

import numpy as np
a=[[1,1],[2,2]]
b=np.asarray(a)
print(type(b))

output:

<class 'numpy.ndarray'>
Raazescythe
  • 83
  • 1
  • 11