Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

Converting Python List to NumPy Array

  • 03 Jan, 2025
  • Com 0
Featured Image of Converting List into Numpy Array

You can convert a Python List to Numpy Array using the “numpy.array()” or “numpy.asarray()” method. 

But why do you need to convert in the first place? The fundamental difference between a List and an Array is within its data structure. Lists store elements as pointers to objects scattered in memory whereas NumPy arrays store elements of the same data type in a contiguous memory block.

If elements are stored next to each other in memory, it improves access time and cache utilization. That’s why arrays are used in machine learning tasks in most cases: because they make them efficient.

The homogeneity of the Numpy array allows for more efficient storage and processing than Python lists.

Method 1: Using numpy.array()

Using np.array() method

The numpy.array() function accepts a list as an argument and returns numpy array elements containing the same elements. It stores elements of the same data types.

This method will always create a new copy, even if it’s already a NumPy array.

import numpy as np

main_list = [11, 21, 31, 41, 51]
main_array = np.array(main_list)

print(type(main_list))  # Output: <class 'list'>
print(type(main_array))  # Output: <class 'numpy.ndarray'>

print(main_array)       # Output: [11 21 31 41 51]

In this code, we imported the numpy library as np and created a list.

Then, we passed a list to the np.array() function and checked the data type using the type() function.

You can see that the list has type <class ‘list’> and numpy array has type <class ‘numpy.ndarray’>.

Specifying Data Types

You can specify the data type while converting to an array using the “dtype” argument.

import numpy as np

float_list = [1.9, 2.1, 3.1]
float_arr = np.array(float_list)

print(type(float_list)) # Output: <class 'list'>
print(type(float_arr)) # Output: <class 'numpy.ndarray'>
print(float_arr.dtype) # Output: float64

int_array = np.array(float_list, dtype=int)
print(int_array) # Output: [1 2 3]
print(int_array.dtype) # Output: int64

You can see that first, we converted the list of float values to an array of float64 values. Then, we converted an array of float64 values to an array of integer values (int64) using the dtype argument.

Nested Lists

The np.array() method automatically handles nested lists and creates the appropriate multi-dimensional array.

import numpy as np

nested_list = [[19, 21, 30], [46, 50, 60], [71, 81, 91]]
nested_arr = np.asarray(nested_list)

print(type(nested_list))  # Output: <class 'list'>
print(type(nested_arr))  # Output: <class 'numpy.ndarray'>

print(nested_arr)   # Output: [[19 21 30]
                    #         [46 50 60]
                    #         [71 81 91]]

Consistent sublist lengths

If the sublists (lists within a list) have different lengths, NumPy will create an array of objects (specifically, an array of lists), which might not be what you intend for numerical operations.

import numpy as np

nested_list = [[19, 21], [46, 50, 60]]
nested_arr = np.array(nested_list)

print(type(nested_list))
print(type(nested_arr))

print(nested_arr)

# ValueError: setting an array element with a sequence. The requested array has an @ 
# inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

You can see that due to varying lengths of lists within a list, we get this error: ValueError: setting an array element with a sequence.

Method 2: Using numpy.asarray()

Using np.asarray() method

The np.asarray() is an intelligent method compared to np.array() because if the input is already a NumPy array with the correct data type and memory layout, numpy.asarray() will return the original array without creating a copy.

import numpy as np

main_list = [11, 21, 31, 41, 51]
main_array = np.asarray(main_list)

print(type(main_list)) # Output: <class 'list'>
print(type(main_array))  # Output: <class 'numpy.ndarray'>

print(main_arr) # Output: [11 21 31 41 51]

That’s all!

Post Views: 28
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

Converting a Pandas DataFrame to Python Dictionary
Converting Floats to Integers in a Pandas DataFrame

Leave a Reply Cancel reply

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

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend