How to convert an array to a list in Python
Learn how to convert a Python array to a list. Explore various methods, tips, real-world applications, and how to debug common errors.

In Python, you often need to convert arrays to lists for greater flexibility. This common task is simple with Python's built-in functions, which offer clear syntax and efficient performance.
Here, you'll explore several conversion techniques, including the list() constructor. You'll also find practical tips, real-world applications, and debugging advice to help you select the right approach.
Using the tolist() method
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
my_list = arr.tolist()
print(my_list)--OUTPUT--[1, 2, 3, 4, 5]
The tolist() method is specifically designed for NumPy arrays, offering a direct way to convert them into standard Python lists. As shown in the example, you simply call the method on your array object. This approach is often preferred for its clarity and because it's an idiomatic part of the NumPy library.
Its key advantage is how it handles multi-dimensional arrays. The method recursively converts nested array structures into nested lists, perfectly preserving the original dimensions. This makes it incredibly reliable for complex data transformations where structure is critical.
Basic conversion techniques
Beyond the NumPy-specific tolist() method, Python provides several built-in tools for converting any array-like structure into a list.
Using the list() constructor
import numpy as np
arr = np.array([10, 20, 30, 40])
my_list = list(arr)
print(my_list)--OUTPUT--[10, 20, 30, 40]
The list() constructor is a versatile, built-in Python function that can convert any iterable object into a list. This includes arrays, tuples, and even strings. Its broad applicability makes it a go-to tool for many conversion tasks.
- It's highly readable and works on any iterable, not just NumPy arrays.
- Unlike
tolist(), it only converts the top level of a multi-dimensional array—the inner elements remain as arrays.
Using list comprehension
import numpy as np
arr = np.array([5, 15, 25, 35])
my_list = [item for item in arr]
print(my_list)--OUTPUT--[5, 15, 25, 35]
List comprehension provides a concise and highly readable syntax for creating lists from iterables. The expression [item for item in arr] builds a new list by looping through each element in the source array, offering a more compact alternative to a traditional for loop.
- It’s especially powerful because you can transform elements during conversion, such as creating a new list with
[item * 2 for item in arr]. - Similar to the
list()constructor, it only converts the top level of a multi-dimensional array, leaving inner arrays intact.
Using the * operator for unpacking
import numpy as np
arr = np.array([7, 14, 21, 28])
my_list = [*arr]
print(my_list)--OUTPUT--[7, 14, 21, 28]
The * operator, also known as the unpacking operator, offers a modern and visually clean way to create a list from an array. The expression [*arr] tells Python to take every item out of arr and place it inside a new list. This syntax is both elegant and efficient for simple conversions.
- It’s a concise approach that’s gained popularity for its readability.
- Like the
list()constructor, it performs a shallow conversion on multi-dimensional arrays, leaving inner structures intact.
Advanced techniques
Beyond the fundamentals, you'll find specialized techniques for handling the complexities of multi-dimensional arrays, different array types, and performance-critical conversions.
Converting multidimensional arrays
import numpy as np
arr_2d = np.array([[1, 2], [3, 4], [5, 6]])
nested_list = arr_2d.tolist()
print(nested_list)--OUTPUT--[[1, 2], [3, 4], [5, 6]]
When you're dealing with multi-dimensional arrays, the tolist() method is the most reliable tool. It's designed to handle nested structures by recursively converting every level of the array into a list, which is essential for preserving your data's original shape.
- This deep conversion ensures the final output is a true nested list, not a mix of lists and arrays.
- In contrast, methods like the
list()constructor only perform a shallow conversion, leaving inner arrays untouched.
Converting arrays from the array module
import array
arr = array.array('i', [10, 20, 30, 40])
my_list = list(arr)
print(my_list)--OUTPUT--[10, 20, 30, 40]
Python's built-in array module lets you create type-specific arrays, like the integer array shown with the type code 'i'. They're more memory-efficient than standard lists but less flexible. Converting them back to a list is straightforward because these array objects are iterable.
- The versatile
list()constructor works perfectly for this conversion. - This approach is ideal when you need the flexibility of a list again, such as adding elements of different data types.
High-performance conversion for large arrays
import numpy as np
import time
large_arr = np.arange(1000000)
start = time.time()
large_list = large_arr.tolist()
end = time.time()
print(f"Converted {len(large_list)} elements in {end-start:.6f} seconds")--OUTPUT--Converted 1000000 elements in 0.084326 seconds
When performance matters, especially with large arrays, the tolist() method is your best bet. It's written in C and is highly optimized for NumPy's internal data structures. This allows it to convert the entire array much faster than methods that loop through each element in Python.
- The speed comes from avoiding Python's interpretation overhead for each item.
- As the example demonstrates, benchmarking is a practical way to measure this efficiency and ensure you're using the most performant tool for the job.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
The array conversion techniques in this article are fundamental building blocks, and Replit Agent can use them to build production-ready tools from a simple description:
- Build a data serialization API that processes NumPy arrays and converts them to JSON lists using
tolist()for web-friendly output. - Create an interactive data dashboard that takes numerical inputs, performs calculations, and then converts the resulting arrays to lists to render charts.
- Deploy a file format converter that reads structured data from an array and transforms it into a nested list for configuration files.
Simply describe your application, and Replit Agent will write the code, run tests, and fix issues automatically. Try Replit Agent to turn your concepts into working software.
Common errors and challenges
Converting arrays can introduce subtle errors, but you can navigate them by understanding data serialization, special values, and memory management.
- A common hurdle is the
TypeErrorthat occurs when trying to serialize a NumPy array directly into JSON. The JSON format doesn't understand NumPy'sndarrayobject, so you must first convert it. Calling thetolist()method on your array transforms it into a standard Python list, which thejsonlibrary can easily handle. - You might also run into trouble with special floating-point values like
NaNandInfinity. While NumPy handles these gracefully, standard JSON does not have a representation for them, leading to errors during serialization. Before converting, you'll need to decide how to handle them—perhaps by replacing them withnull, string representations, or filtering them out entirely. - Finally, be mindful of memory consumption when working with very large arrays. The
tolist()method creates a completely new list, effectively duplicating your data in memory. This can lead to aMemoryErrorif the array is massive. To prevent this, consider processing the array in smaller chunks instead of converting it all at once.
Fixing JSON serialization errors with numpy.ndarray
A common roadblock is the TypeError that arises when you try to serialize a NumPy array with the json library. Because the json.dumps() function doesn't natively understand the numpy.ndarray object, it can't process the data. The code below shows this exact problem in action.
import numpy as np
import json
data = np.array([1, 2, 3, 4, 5])
# This will raise a TypeError
json_string = json.dumps({"data": data})
print(json_string)
The code attempts to pass a NumPy ndarray directly to json.dumps(), which only accepts standard Python types. This mismatch triggers the TypeError. The corrected approach below demonstrates the proper way to serialize the array.
import numpy as np
import json
data = np.array([1, 2, 3, 4, 5])
# Convert to list before serializing
json_string = json.dumps({"data": data.tolist()})
print(json_string)
The solution is to call data.tolist() before passing the data to json.dumps(). This works because the json library doesn't recognize NumPy's ndarray object, which causes a TypeError. The tolist() method transforms the array into a standard Python list—a format that json.dumps() understands perfectly. You'll often encounter this issue when preparing data for web APIs or saving configurations, as JSON is a common data exchange format.
Dealing with NaN and Infinity values in conversion
While NumPy handles special floating-point values like NaN and Infinity, standard JSON does not. This mismatch causes a ValueError during serialization because the JSON format has no equivalent representation. The following code illustrates this exact problem in action.
import numpy as np
import json
arr = np.array([1.0, 2.0, np.nan, np.inf])
my_list = arr.tolist()
# This will raise an error
json_str = json.dumps({"values": my_list})
print(json_str)
The tolist() method converts the array, but the resulting list still contains NaN and Infinity. The json.dumps() function cannot process these special float types, which triggers the error. The corrected code below shows how to handle these values before serialization.
import numpy as np
import json
arr = np.array([1.0, 2.0, np.nan, np.inf])
my_list = arr.tolist()
# Replace special values with null or strings
clean_list = []
for val in my_list:
if np.isnan(val):
clean_list.append(None)
elif np.isinf(val):
clean_list.append("Infinity")
else:
clean_list.append(val)
json_str = json.dumps({"values": clean_list})
print(json_str)
The solution is to clean the list before passing it to json.dumps(). By looping through the list, you can use np.isnan() and np.isinf() to find and replace special values with JSON-friendly alternatives like None—which becomes null—or a string. This is a crucial step when preparing data from scientific computations or external sources, as these values will otherwise break the serialization process.
Preventing memory issues with large array tolist() conversion
Converting a massive array with tolist() can be a memory trap. Since the method creates an entirely new list, it effectively doubles your data's memory footprint, which can trigger a MemoryError. The code below shows this problem in action.
import numpy as np
# Create a large array
huge_arr = np.ones((10000, 10000))
# This may cause memory issues
huge_list = huge_arr.tolist()
print(f"List size: {len(huge_list)} × {len(huge_list[0])}")
The code allocates a massive array with 100 million elements. Calling huge_arr.tolist() then tries to duplicate this entire structure in memory at once, which can easily exhaust available RAM. The corrected approach below avoids this problem.
import numpy as np
# Create a large array
huge_arr = np.ones((10000, 10000))
# Process in manageable chunks
chunk_size = 1000
for i in range(0, huge_arr.shape[0], chunk_size):
chunk = huge_arr[i:i+chunk_size].tolist()
# Process chunk here
print(f"Processing chunk {i//chunk_size + 1}")
The solution avoids a MemoryError by processing the array in manageable chunks. Instead of converting the entire huge_arr at once, the code iterates through it and converts smaller slices to lists individually. This approach keeps memory usage low because you aren't duplicating the entire dataset. You'll find this technique essential when working with large datasets in data science or machine learning, where arrays can easily exceed available RAM and crash your program.
Real-world applications
These conversion skills are essential for practical tasks, from preparing data for web APIs to implementing custom financial calculations.
Converting NumPy arrays to JSON for API integration
In API development, data from sources like sensor readings is often stored in NumPy arrays, and you must use tolist() to convert them into a list before they can be serialized into JSON.
import numpy as np
import json
# Sensor readings as a NumPy array
temperature_data = np.array([22.5, 23.1, 21.8, 24.0, 22.7])
# Convert to list for JSON serialization
json_data = {"temperatures": temperature_data.tolist()}
print(json.dumps(json_data, indent=2))
This example shows how to make NumPy data compatible with the json library. The core issue is that json.dumps() doesn't recognize NumPy's array objects, so a direct conversion would fail.
- First, the
temperature_dataarray is converted into a standard Python list using thetolist()method. - This new list is then used within a dictionary, which
json.dumps()can easily process into a JSON string. - The
indent=2parameter formats the final string for better readability.
Implementing a custom moving average with tolist()
For financial calculations like a moving average, tolist() helps you convert the NumPy array output into a standard list, making it easier to pair with other data for analysis.
import numpy as np
# Stock prices as NumPy array
prices = np.array([105.2, 107.8, 106.5, 108.3, 110.0, 109.2, 111.5])
# Compute 3-day moving average with NumPy
window_size = 3
moving_avg = np.convolve(prices, np.ones(window_size)/window_size, mode='valid')
# Convert to list and pair with corresponding days
result = list(zip(range(window_size, len(prices) + 1), moving_avg.tolist()))
print("Day : 3-Day Moving Average")
for day, avg in result:
print(f"{day}: {avg:.2f}")
This code efficiently calculates a 3-day moving average for stock prices. It leverages NumPy's powerful np.convolve function to handle the sliding window calculation, which is much faster than a manual loop.
- The resulting NumPy array is converted to a list with
tolist(). - The
zip()function then pairs each average with its corresponding day number.
This creates a clean, readable output, demonstrating a practical workflow for time-series analysis where you need to process array data and present it in a structured format.
Get started with Replit
Put these techniques into practice with Replit Agent. Describe a tool like, “Build an API that reads a CSV of numbers and returns it as a JSON list,” or, “Create a dashboard that calculates a moving average and displays it.”
Replit Agent writes the code, tests for errors, and deploys your application directly from your description. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



.png)