Convert Python List to numpy Arrays
Last Updated :
23 Oct, 2024
NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into a numpy array.
Let's start with a basic example to show how we can convert a Python list to a NumPy array.
Python
import numpy as np
a = [1, 2, 3, 4, 5]
# Convert the list to a NumPy array
arr = np.array(a)
print(arr)
Let’s now discuss the different ways of converting a list to an array in more detail.
Using numpy.array()
The numpy.array() function is the most common way to convert a list into an array. It takes the Python list as an argument and returns a NumPy array containing the same elements.
Python
import numpy as np
a = [1.2, 2.6, 3.3, 4.2]
# Convert the list to a NumPy array
arr = np.array(a)
print(arr)
Explanation: We used np.array(a) to convert the list into a NumPy array and storing it in arr.
Using numpy.asarray()
The numpy.asarray() function is another way to convert a list into an array.
Python
import numpy as np
a = [1, 2, 3, 4]
# Convert the list to a NumPy array using asarray
arr = np.asarray(a)
print(arr)
Explanation: We used np.asarray(a) to convert the list into a NumPy array and storing it in arr.
Note:
- In both cases (numpy.array() and numpy.asarray()), a new NumPy array is created from Python list.
- The Python list and resulting NumPy array do not share memory because Python lists and NumPy arrays use different memory management systems.
To know the actual difference between these methods, please refer to "Difference between numpy.array() and numpy.asarray()".
Specifying Data Types in NumPy Arrays
When converting a list to a NumPy array, we can also explicitly specify the data type of the elements using the dtype parameter.
Python
import numpy as np
# List contains float number
a = [1.5, 2.8, 3.1]
# Convert to NumPy array with specified data type (integer)
arr = np.array(a, dtype=int)
print(arr)
Converting Nested Lists to NumPy Arrays
We can also convert nested lists (i.e., lists of lists) into multi-dimensional NumPy arrays. This is particularly useful for representing matrices.
Python
import numpy as np
# Define a nested Python list
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Convert to a 2D NumPy array
mat = np.array(a)
print(mat)
Output[[1 2 3]
[4 5 6]
[7 8 9]]
Explanation: Each inner list becomes a row in the NumPy 2D array and this allow efficient mathematical operations on rows and columns.
Please refer "Convert Python Nested Lists to Multidimensional NumPy Arrays" for deep dive into this topic.
Reshaping NumPy Arrays
After converting a list into a NumPy array, we may want to reshape it. This can be useful for creating matrices or preparing data for machine learning.
Python
import numpy as np
a = [1, 2, 3, 4, 5, 6]
# Convert to NumPy array
arr = np.array(a)
# Reshape the array to 2 rows and 3 columns
resArr = arr.reshape(2, 3)
print(resArr)
Explanation: We reshaped a 1D array into a 2D array with 2 rows and 3 columns.
Please refer "Reshape NumPy Array" for deep dive into this topic.
Combining Multiple Lists into a NumPy Array
We may also need to combine multiple lists into a single NumPy array. This is easily done using np.array().
Python
import numpy as np
# Define multiple Python lists
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
# Combine lists into a single NumPy array
arr = np.array([a, b, c])
print(arr)
Output[[1 2 3]
[4 5 6]
[7 8 9]]
Explanation: Each list becomes a row in a 2D NumPy array, making it easy to handle multiple lists as one unit.
Related Articles:
Similar Reads
How to convert NumPy array to list ? This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding. Convert NumPy Array to List There are various ways to convert NumPy Array to List here we are discussing some generally us
4 min read
Python | Convert Numpy Arrays to Tuples Given a numpy array, write a program to convert numpy array into tuples. Examples - Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]]) Output: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1)) Input: ([['manjeet', 'akshat'], ['nikhil', 'akash']]) Output: (('manjeet', 'akshat'), ('nikhil', 'akash')) Method #1: Using tuple
2 min read
Python Lists VS Numpy Arrays Here, we will understand the difference between Python List and Python Numpy array. What is a Numpy array?NumPy is the fundamental package for scientific computing in Python. Numpy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operati
7 min read
How to Convert images to NumPy array? Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. Â In this article we will see How to Convert images to NumPy array? Mod
6 min read
How to Convert NumPy Matrix to Array In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read
How to convert NumPy array to dictionary in Python? The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers givi
3 min read
Convert Python Nested Lists to Multidimensional NumPy Arrays Prerequisite: Python List, Numpy ndarray Both lists and NumPy arrays are inter-convertible. Since NumPy is a fast (High-performance) Python library for performing mathematical operations so it is preferred to work on NumPy arrays rather than nested lists. Method 1: Using numpy.array(). Approach : Im
2 min read
Ways to Convert a Python Dictionary to a NumPy Array The task of converting a dictionary to a NumPy array involves transforming the dictionaryâs key-value pairs into a format suitable for NumPy. In Python, there are different ways to achieve this conversion, depending on the structure and organization of the resulting array.For example, consider a dic
3 min read
Import Text Files Into Numpy Arrays - Python We have to import data from text files into Numpy arrays in Python. By using the numpy.loadtxt() and numpy.genfromtxt() functions, we can efficiently read data from text files and store it as arrays for further processing.numpy.loadtxt( ) - Used to load text file datanumpy.genfromtxt( ) - Used to lo
3 min read
How To Convert Numpy Array To Tensor? We are given a NumPy array, and our task is to convert it into a TensorFlow tensor. This is useful when integrating NumPy-based data with TensorFlow pipelines, which support acceleration using GPU and TPU. For example, converting [[1, 2], [3, 4]] results in a TensorFlow object that looks like: Pytho
2 min read