Skip to content

NumPy - Array from Existing Data

NumPy - Creating Arrays From Existing Data

Section titled “NumPy - Creating Arrays From Existing Data”

NumPy provides several functions to create new arrays based on existing data structures like Python lists, tuples, or raw memory buffers.

This function converts various Python sequence types (lists, tuples, lists of tuples, etc.) into a NumPy ndarray. It’s similar to numpy.array(), but asarray() avoids making a copy if the input is already an ndarray of the desired dtype.

numpy.asarray(a, dtype=None, order=None)

Parameters:

ParameterDescription
aInput data, typically a Python list, tuple, or other sequence.
dtypeOptional. Desired data type for the output array. If not specified, NumPy infers it from the input data.
orderOptional. Memory layout: ‘C’ (row-major, default) or ‘F’ (column-major).

Use asarray() when you want to ensure you have an ndarray but want to avoid unnecessary data copying if the input is already suitable.

Basic conversion of a Python list.

import numpy as np
my_list = [1, 2, 3]
a = np.asarray(my_list)
print(a)
print(type(a))

Output:

[1 2 3]
<class 'numpy.ndarray'>

Converting a list and setting the data type to float.

import numpy as np
my_list = [1, 2, 3]
a = np.asarray(my_list, dtype=float)
print(a)
print(a.dtype)

Output:

[1. 2. 3.]
float64

Converting a Python tuple works similarly.

import numpy as np
my_tuple = (1, 2, 3)
a = np.asarray(my_tuple)
print(a)

Output:

[1 2 3]

If inner sequences have different lengths, the resulting array will have dtype=object.

import numpy as np
list_of_tuples = [(1, 2, 3), (4, 5)] # Note: inner tuples have different lengths
a = np.asarray(list_of_tuples)
print(a)
print(a.dtype)

Output:

[(1, 2, 3) (4, 5)]
object

This function creates a 1D ndarray by interpreting data from a buffer object (like bytes) directly, without copying data. Useful for handling binary data or interfacing with low-level libraries.

numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)

Parameters:

ParameterDescription
bufferAn object exporting the buffer interface (e.g., bytes, bytearray).
dtypeData type of the elements to interpret from the buffer.
countNumber of items to read. -1 (default) means read as many as possible.
offsetStart reading the buffer from this offset (in bytes).

Interpreting a byte string as an array of single-byte characters.

import numpy as np
# Create a byte string (note the 'b' prefix)
s = b'Hello World'
# Interpret the buffer as an array of 1-byte strings ('S1')
a = np.frombuffer(s, dtype='S1')
print(a)

Output:

[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

Note: Modifying the array created by frombuffer will modify the original buffer if it’s mutable (like a bytearray).

Creates a 1D ndarray by consuming items from any Python iterable (like generators, lists, range objects). This can be memory-efficient for large sequences, as it doesn’t require the entire sequence to exist in memory at once (if the iterable yields items one by one).

numpy.fromiter(iterable, dtype, count=-1)

Parameters:

ParameterDescription
iterableAny Python object that can be iterated over.
dtypeData type of the resulting array. This must be specified.
countNumber of items to read from the iterator. -1 (default) means consume all items.

First, let’s see a standard Python list created using range().

# Create a standard Python list using range in Python 3
# (range itself is an iterable, list() consumes it)
my_list = list(range(5))
print(my_list)

Output:

[0, 1, 2, 3, 4]

Creating an ndarray directly from the range iterable.

import numpy as np
# Create an iterable (range object)
iterable = range(5)
# Use the iterator to create an ndarray with float dtype
x = np.fromiter(iterable, dtype=float)
print(x)
print(x.dtype)

Output:

[0. 1. 2. 3. 4.]
float64