Convert a List into NumPy Arrays
These are the methods by which we can convert a list into NumPy Arrays in Python.
- Using numpy.asarray()
- Using numpy.array()
Convert a List into NumPy Arrays using numpy.asarray()
numpy.asarray() method converts the input list into NumPy array. In this example, we are converting Python list into NumPy array by using numpy.asarray().
Python3
import numpy as np # list list1 = [ 3 , 4 , 5 , 6 ] print ( type (list1)) print (list1) print () # conversion array1 = np.asarray(list1) print ( type (array1)) print (array1) print () |
Output:
<class 'list'>
[3, 4, 5, 6]
<class 'numpy.ndarray'>
[3 4 5 6]
Convert a List into NumPy Arrays using numpy.array()
numpy.array() method converts the input list into NumPy array. In this example, we are converting the Python list into NumPy array by using numpy.array().
Python3
import numpy as np # list list1 = [ 1 , 2 , 3 ] print ( type (list1)) print (list1) print () # conversion array1 = np.array(list1) print ( type (array1)) print (array1) print () |
Output:
<class 'list'>
[1, 2, 3]
<class 'numpy.ndarray'>
[1 2 3]
How to convert a list and tuple into NumPy arrays?
In this article, let’s discuss how to convert a list and tuple into arrays using NumPy. NumPy provides various methods to do the same using Python.
Example:
Input: [3, 4, 5, 6]
Output: [3 4 5 6]
Explanation: Python list is converted into NumPy Array
Input: ([8, 4, 6], [1, 2, 3])
Output: [[8 4 6]
[1 2 3]]
Explanation: Tuple is converted into NumPy Array