Convert Python List to NumPy Arrays

Hello everyone, today we’ll be talking about converting Python lists to a NumPy Arrays.

Lists are dynamic arrays that can store elements of different types and also doesn’t need to the predefined size of the array, unlike the arrays which we use in C++ or Java. However, due to these features, lists have a reduced performance.

Python is one of the most widely used languages in the fields like Data Science, Artificial Intelligence and Scientific Computing. For a better runtime performance and better memory management, we use another array-like data structure known as NumPy arrays provided by the NumPy module.

NumPy arrays are similar to the basic array data structure. They store only homogeneous elements and are very efficient in handling the multi-dimensional arrays. They are also efficient in handling a huge number of elements.

Conversion of Python Lists to NumPy Arrays

To convert a Python list in a NumPy array, we can use two methods: NumPy.array() and NumPy.asarray().

UsingĀ numpy.array():

This method creates a copy of the given array and returns a new object.

>>> a = [1, 2, 3, 4]
>>> np.array(a)
array([1, 2, 3, 4])

UsingĀ numpy.asarray():

This method doesn’t create a copy of the given array.

>>> a = [1, 2, 3, 4]
>>> np.asarray(a)
array([1, 2, 3, 4])

Hope you like this post.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *