Here are three ways to convert a list to an array in Python:
- Using numpy.array()
- Using np.asarray()
- Using Built-in array Module
Method 1: Using numpy.array()
The np.array() function takes a list as an argument and returns a NumPy array containing all the elements of the list.
NumPy arrays are particularly useful for high-performance computing tasks, especially those involving large datasets and mathematical operations.
Visual Representation
Example
import numpy as np
# Creating a list
num_list = [11, 21, 19, 18, 29]
print(num_list)
print(type(num_list))
# Converting the list to a NumPy array
num_array = np.array(num_list)
print(num_array)
print(type(num_array))
Output
[11, 21, 19, 18, 29]
<class 'list'>
[11 21 19 18 29]
<class 'numpy.ndarray'>
Method 2: Using numpy.asarray()
The np.asarray() function, similar to np.array(), does not copy the data if the original object is already an array, making it more efficient in scenarios where avoiding unnecessary data copying is beneficial.
Visual Representation
Example
import numpy as np
# Creating a list
num_list = [11, 21, 19, 18, 29]
print(num_list)
print(type(num_list))
num_array = np.asarray(num_list)
print(num_array)
print(type(num_array))
Output
[11, 21, 19, 18, 29]
<class 'list'>
[11 21 19 18 29]
<class 'numpy.ndarray'>
Method 3: Using Built-in array Module
To use the array() function from the array module, you need to import the array module and then provide two arguments: the data type of the array elements and the list to be converted.
The ‘i’ argument specifies the type of the array elements as integers.
Visual Representation
Example
from array import array
# Creating a list
num_list = [11, 21, 19, 18, 29]
print(num_list)
print(type(num_list))
num_array = array('i', num_list)
print(num_array)
print(type(num_array))
Output
[11, 21, 19, 18, 29]
<class 'list'>
array('i', [11, 21, 19, 18, 29])
<class 'array.array'>
Gomeaning
This is a great tutorial! I’ve been struggling with this for a while.