How to transform (convert) a list to an array in python ?

Published: February 04, 2019

DMCA.com Protection Status

In python, to convert a list to an array, a solution is to use the numpy function called asarray(), example:

>>> l = [4,1,7,3,2]
>>> type(l)
<type 'list'>
>>> import numpy as np
>>> A = np.asarray(l)
>>> A
array([4, 1, 7, 3, 2])
>>> type(A)
<type 'numpy.ndarray'>
>>> len(l)
5
>>> A.shape
(5,)
>>> A.dtype
dtype('int32')

Note: To change the shape of matrix A from (5,) to (5,1) just add the following line:

>>> A = A[:,np.newaxis]
>>> A.shape
(5,1)

Another example:

>>> l = ['a','b','c','d','e','f']
>>> A = np.asarray(l)
>>> A
array(['a', 'b', 'c', 'd', 'e', 'f'], 
  dtype='|S1')
>>> A.dtype
dtype('|S1')

References

Links Site
asarray() numpy doc
Python - List to array stackoverflow
In-place type conversion of a NumPy array stackoverflow