Python NumPy: How to Convert a List and Tuple into NumPy Arrays
Converting Python lists and tuples into NumPy arrays is one of the most fundamental operations when working with numerical data in Python. NumPy arrays offer significant advantages over standard Python sequences - they're faster for mathematical operations, consume less memory, and provide a rich set of functions for data manipulation.
In this guide, you'll learn how to convert lists and tuples to NumPy arrays using np.array() and np.asarray(), understand the differences between these methods, and handle common conversion scenarios.
Converting a List to a NumPy Array
Using np.array()
The np.array() function is the most common way to create a NumPy array from a Python list:
import numpy as np
my_list = [3, 4, 5, 6]
arr = np.array(my_list)
print(f"Original list: {my_list}")
print(f"Type: {type(my_list)}")
print(f"\nNumPy array: {arr}")
print(f"Type: {type(arr)}")
print(f"Dtype: {arr.dtype}")
Output:
Original list: [3, 4, 5, 6]
Type: <class 'list'>
NumPy array: [3 4 5 6]
Type: <class 'numpy.ndarray'>
Dtype: int64
Using np.asarray()
The np.asarray() function also converts a list to a NumPy array:
import numpy as np
my_list = [10, 20, 30, 40]
arr = np.asarray(my_list)
print(f"NumPy array: {arr}")
print(f"Type: {type(arr)}")
Output:
NumPy array: [10 20 30 40]
Type: <class 'numpy.ndarray'>
Converting a Tuple to a NumPy Array
Both functions work identically with tuples:
Using np.array()
import numpy as np
my_tuple = (1, 2, 3, 4, 5)
arr = np.array(my_tuple)
print(f"Original tuple: {my_tuple}")
print(f"Type: {type(my_tuple)}")
print(f"\nNumPy array: {arr}")
print(f"Type: {type(arr)}")
Output:
Original tuple: (1, 2, 3, 4, 5)
Type: <class 'tuple'>
NumPy array: [1 2 3 4 5]
Type: <class 'numpy.ndarray'>
Converting a Tuple of Lists (2D Array)
A tuple containing lists of equal length creates a 2D array:
import numpy as np
my_tuple = ([8, 4, 6], [1, 2, 3])
arr = np.array(my_tuple)
print(f"Original tuple: {my_tuple}")
print(f"\nNumPy array:")
print(arr)
print(f"Shape: {arr.shape}")
Output:
Original tuple: ([8, 4, 6], [1, 2, 3])
NumPy array:
[[8 4 6]
[1 2 3]]
Shape: (2, 3)
Key Difference: np.array() vs np.asarray()
Both functions produce the same result when converting lists or tuples. The critical difference appears when the input is already a NumPy array:
np.array()always creates a new copy of the data.np.asarray()returns the same array without copying (if possible).
import numpy as np
original = np.array([1, 2, 3])
# np.array() creates a copy
copy_arr = np.array(original)
copy_arr[0] = 99
print(f"Original after np.array modification: {original}") # Unchanged
# np.asarray() does NOT create a copy
original = np.array([1, 2, 3])
same_arr = np.asarray(original)
same_arr[0] = 99
print(f"Original after np.asarray modification: {original}") # Changed!
Output:
Original after np.array modification: [1 2 3]
Original after np.asarray modification: [99 2 3]
- Use
np.array()when you need a guaranteed independent copy of the data. - Use
np.asarray()when you want to avoid unnecessary copying for better performance - especially in functions that might receive either lists or existing arrays as input.
Specifying the Data Type
Both functions accept a dtype parameter to control the output array's data type:
import numpy as np
int_list = [1, 2, 3, 4, 5]
# Convert to float
float_arr = np.array(int_list, dtype=float)
print(f"As float: {float_arr}")
# Convert to float32 for memory efficiency
f32_arr = np.array(int_list, dtype=np.float32)
print(f"As float32: {f32_arr}")
# Convert to string
str_arr = np.array(int_list, dtype=str)
print(f"As string: {str_arr}")
Output:
As float: [1. 2. 3. 4. 5.]
As float32: [1. 2. 3. 4. 5.]
As string: ['1' '2' '3' '4' '5']
Converting Nested Lists to Multi-Dimensional Arrays
Nested lists create multi-dimensional arrays automatically:
import numpy as np
# 2D array from nested list
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print("2D Array:")
print(matrix)
print(f"Shape: {matrix.shape}\n")
# 3D array from deeply nested list
tensor = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
print("3D Array:")
print(tensor)
print(f"Shape: {tensor.shape}")
Output:
2D Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Shape: (3, 3)
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Shape: (2, 2, 2)
Handling Mixed Data Types
When a list contains mixed types, NumPy casts all elements to a common type:
import numpy as np
# Integers and floats: promotes to float
mixed = np.array([1, 2.5, 3, 4.7])
print(f"Int + Float: {mixed} (dtype: {mixed.dtype})")
# Numbers and strings: promotes to string
mixed2 = np.array([1, 'hello', 3.14])
print(f"Mixed types: {mixed2} (dtype: {mixed2.dtype})")
Output:
Int + Float: [1. 2.5 3. 4.7] (dtype: float64)
Mixed types: ['1' 'hello' '3.14'] (dtype: <U32)
If sublists have different lengths, NumPy creates a 1D array of Python objects instead of a proper multi-dimensional array:
import numpy as np
ragged = np.array([[1, 2, 3], [4, 5]], dtype=object)
print(f"Array: {ragged}")
print(f"Shape: {ragged.shape}")
print(f"Dtype: {ragged.dtype}")
Output:
Array: [list([1, 2, 3]) list([4, 5])]
Shape: (2,)
Dtype: object
This loses all the performance benefits of NumPy. Ensure all sublists have the same length for proper multi-dimensional arrays.
Practical Example: Converting Data for Computation
A common workflow is converting Python data to NumPy arrays for efficient computation:
import numpy as np
# Raw data as Python lists
temperatures_celsius = [20, 25, 30, 35, 22, 28, 33]
humidity_percent = (45, 50, 55, 60, 48, 52, 58)
# Convert to NumPy arrays
temp = np.array(temperatures_celsius, dtype=float)
humidity = np.array(humidity_percent, dtype=float)
# Perform vectorized operations
temp_fahrenheit = temp * 9/5 + 32
print(f"Celsius: {temp}")
print(f"Fahrenheit: {temp_fahrenheit}")
print(f"Humidity: {humidity}")
print(f"\nAvg temp: {temp.mean():.1f}°C")
print(f"Avg humidity: {humidity.mean():.1f}%")
Output:
Celsius: [20. 25. 30. 35. 22. 28. 33.]
Fahrenheit: [68. 77. 86. 95. 71.6 82.4 91.4]
Humidity: [45. 50. 55. 60. 48. 52. 58.]
Avg temp: 27.6°C
Avg humidity: 52.6%
Quick Comparison
| Feature | np.array() | np.asarray() |
|---|---|---|
| Converts lists/tuples | ✅ | ✅ |
| Creates copy from list | ✅ | ✅ |
| Creates copy from ndarray | ✅ (always copies) | ❌ (no copy if possible) |
Supports dtype parameter | ✅ | ✅ |
| Best for | Creating independent arrays | Avoiding unnecessary copies |
Conclusion
Converting Python lists and tuples to NumPy arrays is simple and essential for numerical computing:
- Use
np.array()for the most common conversion - it always creates a fresh NumPy array from any list or tuple. - Use
np.asarray()when performance matters and you want to avoid unnecessary data copying, especially in functions that accept both lists and existing arrays. - Specify the
dtypeparameter to control the output data type explicitly. - Ensure nested lists have equal lengths to create proper multi-dimensional arrays.
Both functions handle 1D, 2D, and higher-dimensional data seamlessly, making them the go-to tools for bridging Python's built-in data structures with NumPy's powerful array operations.