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.

Initialising a numpy array of unknown length

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

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.

For this purpose, 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 code 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 »



ADVERTISEMENT
ADVERTISEMENT


What's New (MCQs)



Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.