Initialise numpy array of unknown length

Learn, how to initialise numpy array of unknown length in Python?
Submitted by Pranit Sharma, on January 21, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Sometimes, we need to build NumPy arrays of unknown size to work with them in the future.

Problem statement

Suppose we want to build a NumPy array on the fly, and we do not know the size of this array in advance, the array would result in a new array containing all the elements that lie in some range.

Initialising a numpy array of unknown length

To initialise numpy array of unknown length, we can build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to the array, for a total of O(n).

Let us understand with the help of an example,

Python program to initialise numpy array of unknown length

# Import numpy
import numpy as np

# Creating a list
l = []

# Appending elements in l
for i in range(10):
        l.append(i)

# Converting list into numpy array
arr = np.array(l)

# Display numpy array
print("Created numpy array:\n",arr)

Output

Example: Initialise numpy array of unknown length

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.