# How to convert a list to a matrix using numpy in python ?

Published: July 27, 2020

Tags: Python; Numpy;

Examples of how to convert a list to a matrix using numpy in python:

### Create a list in python

Lets consider for example the following list

````l = [4,1,7,3,2]`
```

Note: to check the type of a variable in python we can use the function type():

````type(l)`
```

which returns here:

````<type 'list'>`
```

### Convert a list of numbers to a matrix

To convert a list of numbers to a matrix, as solution is to use the numpy function asarray(): illustration:

````import numpy as np`

`A = np.asarray(l)`

`print(A)`
```

gives

````array([4, 1, 7, 3, 2])`
```

and

````type(A)`
```

gives

````<type 'numpy.ndarray'>`
```

Note: to check the length of the input list:

````len(l)`
```

returns

````5`
```

end the matrix dimensions

````A.shape`
```

returns

````(5,)`
```

and the matrix type:

````A.dtype`
```

returns

````dtype('int32')`
```

### Convert a list of strings to a matrix

Work also to convert a list of strings to a matrix:

````  l = ['a','b','c','d','e','f']`
`  A = np.asarray(l)`
`  print(A)`
```

gives

````  array(['a', 'b', 'c', 'd', 'e', 'f'], `
`    dtype='|S1')`
```

### Convert a list of strings to a matrix using numpy.array()

Amother solution using numpy.array()

````import numpy as np`

`l = [1,2,3,4]`

`A = np.array(l)`
```

returns

````array([1, 2, 3, 4])`
```