How to Convert List to Array in Python

To convert a list to an array in Python, you can use the array module or the numpy library.

The following examples show how to convert a list to an array in Python using these two methods.

Using array Module

We can use the array() function from the array module to convert a list to an array.

Suppose we have the following list:

import array

# Declare list
list_ = [1, 2, 3, 4, 5]

# Convert list to array
arr = array.array('i', list_)

# Show array
print("Array:", arr)

Output: 👇️

Array: array('i', [1, 2, 3, 4, 5])

In this example, we use the array() function from the array module to convert the list list_ to an array arr. The output shows the array created by converting the list to an array.

Using numpy Library

We can use the numpy.array() function from the numpy library to convert a list to an array.

Suppose we have the following list:

import numpy as np

# Declare list
list_ = [1, 2, 3, 4, 5]

# Convert list to array
arr = np.array(list_)

# Show array
print("Array:", arr)

Output: 👇️

Array: [1 2 3 4 5]

In this example, we use the numpy.array() function from the numpy library to convert the list list_ to an array arr. The output shows the array created by converting the list to an array.

Conclusion

We can use the array() function from the array module or the numpy.array() function from the numpy library to convert a list to an array in Python. These methods provide a convenient way to transform lists into arrays.