How to convert an array to a list in Python

Discover how to convert a Python array to a list. Explore methods, tips, real-world applications, and how to debug common errors.

How to convert an array to a list in Python
Published on: 
Tue
Mar 3, 2026
Updated on: 
Wed
Apr 1, 2026
The Replit Team

In Python, you'll often convert arrays to lists to gain more flexibility. While arrays have a fixed size, lists are dynamic and better suited for many data manipulation tasks.

In this article, we'll show you key techniques like the list() constructor and list comprehensions. We'll also provide performance tips, real-world examples, and debugging advice for a smooth workflow.

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 the most straightforward approach for converting a NumPy array to a standard Python list. It's a method that belongs to the NumPy array object itself, making the syntax clean and intuitive.

In the code, after creating the NumPy array arr, we simply call arr.tolist(). This action returns a new Python list containing all the elements from the original array, which we then store in my_list. This is often the preferred method for its clarity and directness.

Basic conversion techniques

While the tolist() method is often the go-to, Python also provides other versatile, built-in techniques for converting arrays to lists.

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 another effective way to convert an array. This built-in Python function takes any iterable object—like a NumPy array—and creates a new list from its elements. You simply pass the array as an argument, as shown with list(arr).

  • This method is highly versatile since it works on any iterable, not just NumPy arrays.

It's a fundamental Python tool that you'll find useful in many different scenarios beyond array conversion.

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 offers a concise and highly readable way to create a new list from an existing iterable. The syntax [item for item in arr] loops through each item in the array, adding it to the new list one by one. It's often considered a more "Pythonic" approach for its elegant structure.

  • This method is especially powerful because it lets you modify elements during the conversion. For example, you could create a new list with doubled values using [item * 2 for item in arr].

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 syntax for this conversion. When you use [*arr], the operator effectively unpacks each element from the array, and the surrounding square brackets [] collect them into a new list.

  • This method is highly readable and concise, making it a popular choice in modern Python for its expressive power when working with any iterable.

Advanced techniques

With the fundamentals covered, you can now tackle more advanced conversions for multidimensional arrays, arrays from the array module, and performance-sensitive applications.

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 working with multidimensional arrays, the tolist() method is your best friend. It recursively converts each dimension of the NumPy array into a list. This means a 2D array, like arr_2d, becomes a list of lists, perfectly preserving its nested structure.

  • Unlike the list() constructor, which would only convert the outer dimension, tolist() ensures every element is converted. This gives you a true nested Python list, which is exactly what you usually need.

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 array.array('i', ...). While these are more memory-efficient than standard lists, they're also less flexible. For this conversion, the list() constructor is your best option.

  • Because array objects are iterable, the list() constructor can easily loop through their elements to build a new, standard Python list. This highlights how versatile the constructor is for any iterable type, not just NumPy arrays.

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 you're dealing with large arrays, performance is key. The tolist() method is highly optimized for speed because it's implemented in C under the hood. This low-level implementation makes it significantly faster than methods that iterate in Python, like the list() constructor or a list comprehension.

  • For datasets with thousands or millions of elements, using tolist() ensures the conversion is as efficient as possible, minimizing bottlenecks in your data processing pipelines.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This environment lets you move from piecing together techniques to building complete applications with Agent 4. It's a tool that takes your idea to a working product—handling the code, databases, APIs, and deployment directly from your description.

Instead of piecing together techniques like converting arrays, you can describe the final application you want to build:

  • A data clean-up tool that converts a NumPy array of raw numbers into a Python list while filtering out invalid entries.
  • A report generator that takes a 2D NumPy array of sales data and converts it into a nested list to display in a web-based table.
  • A simple API endpoint that receives numerical data as an array, converts it to a list, and returns it as a JSON response.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While converting arrays is often easy, you can encounter tricky errors with data types, special values, and memory management.

Fixing JSON serialization errors with numpy.ndarray

A common roadblock is a TypeError when trying to serialize a NumPy array directly into JSON. The standard JSON encoder doesn't recognize NumPy's specific data types, so you need to convert the array first. Simply call the tolist() method on your array before passing it to a function like json.dumps(). This turns the array into a standard Python list, which JSON can handle without any issues.

Dealing with NaN and Infinity values in conversion

You also need to be careful with special numeric values. NumPy arrays can include NaN (Not a Number) and Infinity, which don't have direct equivalents in the standard JSON format. While tolist() conveniently converts NaN to None, it leaves Infinity as a float value that isn't valid in JSON and will cause an error during serialization.

  • To avoid this, it's best practice to clean your array before conversion. You can replace any NaN or Infinity values with None or another placeholder that your application can correctly interpret.

Preventing memory issues with large array tolist() conversion

Finally, performance can become a challenge with very large arrays. Since tolist() creates a new copy of your data as a list, it can temporarily double your memory footprint. For an array with millions of elements, this can lead to significant memory pressure or even cause your program to crash.

  • If you're working in a memory-constrained environment, consider processing the array in smaller chunks instead of converting it all at once. This allows you to manage memory more effectively by avoiding having both the full array and the full list in memory at the same time.

Fixing JSON serialization errors with numpy.ndarray

Fixing JSON serialization errors with numpy.ndarray

You might run into a TypeError when trying to convert a NumPy array directly to a JSON string. The standard json library can't handle NumPy's data types out of the box. See what happens when you try it in the code below.

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 json.dumps() function can't process the numpy.ndarray object directly, as it only works with standard Python types. See how to correctly prepare the array for serialization in the code that follows.

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 the tolist() method on your array before passing it to json.dumps(). This simple step converts the NumPy array into a standard Python list, which the JSON encoder can process without issue. You'll often run into this TypeError when building APIs or saving data that involves NumPy objects, so it's a good practice to convert them first to ensure compatibility.

Dealing with NaN and Infinity values in conversion

NumPy arrays can contain special values like NaN and Infinity, which don't always play well with other libraries. When you convert an array with tolist(), NaN becomes None, but Infinity values will cause an error during JSON serialization. See what happens below.

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 json.dumps() function fails because while np.nan becomes None, np.inf is converted to a float inf value, which isn't a valid JSON token. See how to properly clean the array before serialization in the code below.

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 manually clean the list after converting it with tolist(). The code iterates through the new list, using np.isnan() and np.isinf() to find special values. It replaces NaN with None and Infinity with a JSON-compatible string like "Infinity". This pre-processing step ensures your data can be successfully serialized by json.dumps() without errors. It's a common issue when working with scientific or financial datasets where these values appear.

Preventing memory issues with large array tolist() conversion

While the tolist() method is efficient, it's not always memory-friendly. It creates a full copy of the array, which can double your program's memory footprint. With massive arrays, this can lead to performance issues or even a crash. The code below demonstrates this potential problem.

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 array in this example contains 100 million items. Using tolist() forces the creation of a second, equally large object in memory, which can cause a failure. See a more memory-efficient technique in the code below.

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}")

To avoid memory errors, the solution processes the array in smaller pieces instead of all at once. The code loops through the huge_arr in manageable chunks defined by chunk_size. During each pass, it slices a portion of the array and converts only that smaller segment to a list with tolist(). This chunking technique is essential when you're handling massive datasets, as it prevents your program from crashing by keeping memory usage low.

Real-world applications

Now that you can navigate common errors, you can use these conversion techniques for practical applications like API integration and data analysis.

Converting NumPy arrays to JSON for API integration

A classic example of this in action is when you're working with an API that needs to return data, like sensor readings, in a standard JSON format.

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 prepare a NumPy array for JSON serialization. The standard json.dumps() function can't process NumPy's array type directly, which would otherwise cause a TypeError.

To solve this, you first convert the temperature_data array into a standard Python list using the tolist() method. Once the data is in a list format, it can be included in a dictionary and successfully serialized into a clean JSON string. This is a common pattern for ensuring data compatibility between different libraries.

Implementing a custom moving average with tolist()

In financial analysis, you can combine NumPy's powerful calculations with the flexibility of tolist() to format complex results like a moving average.

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 calculates a 3-day moving average for a list of stock prices. It uses NumPy’s powerful np.convolve function to efficiently compute the average across a sliding window of data, producing a new NumPy array with the results.

  • The resulting array is then converted into a standard Python list using the tolist() method.
  • Finally, the zip() function pairs each averaged value with its corresponding day number, making the data easy to display or process further.

Get started with Replit

Turn these techniques into a real tool. Describe what you want to build for Replit Agent, like “a data-cleaning script that converts an array to a list” or “an API that returns NumPy data as JSON.”

It will write the code, test for errors, and deploy your application from your description. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Get started for free

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.