Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Initialize an Empty Array of given Length using Python
An empty array consists of either null values or no elements. Empty arrays are useful when you need to initialize storage before populating it with data. Python provides several methods to create empty arrays of a given length using built-in functions and libraries.
Using Multiplication (*) Operator
The multiplication operator repeats elements to create an array of specified length ?
length = 5
arr = [None] * length
print("Empty array using multiplication operator:")
print(arr)
print("Length:", len(arr))
Empty array using multiplication operator: [None, None, None, None, None] Length: 5
Using NumPy empty() Function
NumPy's empty() function creates an uninitialized array of given shape and data type ?
import numpy as np
# Create empty array with object dtype
arr = np.empty(5, dtype=object)
print("Empty array using NumPy:")
print(arr)
# Create empty array with float dtype
float_arr = np.empty(3, dtype=float)
print("Empty float array:")
print(float_arr)
Empty array using NumPy: [None None None None None] Empty float array: [0. 0. 0.]
Using range() and append()
Combine range() with append() to build an empty array iteratively ?
length = 5
arr = []
for i in range(length):
arr.append(None)
print("Empty array using range() and append():")
print(arr)
print("Length:", len(arr))
Empty array using range() and append(): [None, None, None, None, None] Length: 5
Using List Comprehension
List comprehension provides a concise way to create empty arrays ?
length = 4
arr = [None for _ in range(length)]
print("Empty array using list comprehension:")
print(arr)
# Create array of empty lists
nested_arr = [[] for _ in range(3)]
print("Array of empty lists:")
print(nested_arr)
Empty array using list comprehension: [None, None, None, None] Array of empty lists: [[], [], []]
Comparison
| Method | Performance | Memory Usage | Best For |
|---|---|---|---|
| Multiplication (*) | Fastest | Low | Simple cases |
| NumPy empty() | Fast | Very Low | Numerical data |
| List comprehension | Good | Low | Complex initialization |
| range() + append() | Slower | Higher | Learning purposes |
Conclusion
Use multiplication operator [None] * length for simple empty arrays. For numerical computations, prefer NumPy's empty() function. List comprehension offers flexibility for complex initialization patterns.
