Open In App

How to convert a list and tuple into NumPy arrays?

Last Updated : 23 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Convert a List into NumPy Arrays

These are the methods by which we can convert a list into NumPy Arrays in Python.

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]

Convert a Tuple into NumPy Arrays

These are the methods by which we can convert a tuple into NumPy Arrays.

Convert a Tuple into NumPy Arrays using numpy.asarray()

numpy.asarray() method converts the input tuple into NumPy array. In this example, we are converting the Python tuple into NumPy array by using numpy.asarray().

Python3




# tuple
tuple1 = ([8, 4, 6], [1, 2, 3])
print(type(tuple1))
print(tuple1)
print()
 
# conversion
array2 = np.asarray(tuple1)
print(type(array2))
print(array2)


Output:

<class 'tuple'> 
([8, 4, 6], [1, 2, 3])
<class 'numpy.ndarray'>
[[8 4 6]
[1 2 3]]

Convert a Tuple into NumPy Arrays using numpy.array()

numpy.array() method convert input tuple into NumPy array. In this example, we are converting the Python tuple into NumPy array by using numpy.array().

Python3




# tuple
tuple1 = ([8, 4, 6], [1, 2, 3])
print(type(tuple1))
print(tuple1)
print()
 
# conversion
array2 = np.array(tuple1)
print(type(array2))
print(array2)


Ouput:

<class 'tuple'> 
([8, 4, 6], [1, 2, 3])
<class 'numpy.ndarray'>
[[8 4 6]
[1 2 3]]



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads