Python - Convert an array to an ordinary list with the same items
In Python, we often work with different array-like structures such as arrays, NumPy arrays, or regular lists. Sometimes, we need to convert these arrays to a simple Python list for easier manipulation or compatibility with other functions.
Using list() constructor
list() function is the most straightforward way to convert different types of array-like objects into a Python list. It works for regular lists, tuples, and even arrays.
import array
# Example with a regular array
a = array.array('i', [1, 2, 3, 4])
# Convert the array to a list using list()
b = list(a)
# 'b' is now a simple list containing the same elements as 'a'
print(b)
Output
[1, 2, 3, 4]
Other methods that we can use to convert an array to a simple list in Python are:
Table of Content
Using tolist()
If we are working with a NumPy array, we can use the tolist() method to convert it into a regular Python list. NumPy arrays are commonly used for numerical data and large datasets.
import numpy as np
# Example with a NumPy array
a = np.array([1, 2, 3, 4])
# Convert the NumPy array to a list using tolist()
b = a.tolist()
# 'b' is now a simple Python list containing the same elements as 'a'
print(b)
Output
[1, 2, 3, 4]
Using List Comprehension
List comprehension can be used when we want to convert an array-like object to a list while also transforming or filtering the data during the conversion.
import array
# Example with an array.array
a = array.array('i', [1, 2, 3, 4])
# Convert to list using list comprehension
b = [item for item in a]
# 'b' now contains the same items as 'a'
print(b)
Output
[1, 2, 3, 4]
Using extend()
If we have an existing list and we want to add items from another array-like object (such as array.array or NumPy array), we can use the extend() method.
import numpy as np
# Example with a NumPy array and an empty list
a = np.array([1, 2, 3, 4])
b = []
# Use 'extend' to add items from 'a' into 'b'
b.extend(a)
# 'b' now contains all elements from 'a'
print(b)
Output
[1, 2, 3, 4]