How do you create an empty array in python?

How do you create an empty array in python?

Numpy empty() function creates a new array of given shapes and types without initializing entries. On the other side, it requires the user to set all the values in the array manually and should be used with caution. A Numpy array is a very diverse data structure from a list and is designed to be used differently.

Understanding Numpy array

Numpy array is the central data structure of the Numpy library. On a structural level, an array is nothing but pointers. It’s a combination of the memory address, data type, shape, and strides. To make a numpy array, you can use the np.array() function. All you need to do is pass a list to it, and optionally, you can also specify the data type of the data.

import numpy as np

list = ['Python', 'Golang', 'PHP', 'Javascript']
arr = np.array(list)
print(arr)

Output

['Python' 'Golang' 'PHP' 'Javascript']

As you can see in the output, we have created a list of strings and then passed the list to the np.array() function, and as a result, it will create a numpy array.

To create a numpy empty array, we can pass the empty list to the np.array() function, making the empty array. Numpy empty, unlike the zeros() method, does not set array values to zero and may, hence, be marginally faster.

import numpy as np

list = []
arr = np.array(list)
print(arr)

Output

[]

You can see that we have created an empty array using the np.array().

We can also check its data type.

import numpy as np

list = []
arr = np.array(list)
print(arr.dtype)

Output

float64

np.empty

The np.empty(shape, dtype=float, order=’C’) is a numpy array function that returns a new array of given shape and type, without initializing entries. To create an empty array in Numpy (e.g., a 2D array m*n to store), in case you don’t know m how many rows you will add and don’t care about the computational cost, then you can squeeze to 0 the dimension to which you want to append to arr = np.empty(shape=[0, n]).

import numpy as np

arr = np.empty([0, 2])
print(arr)

Output

[]

How to initialize an Efficiently numpy array

NumPy arrays are stored in the contiguous blocks of memory. Therefore, if you need to append rows or columns to an existing array, the entire array must be copied to the new memory block, creating gaps for the new items to be stored. This is very inefficient if done repeatedly to create an array.

In adding rows, this is the best case if you have to create the array as big as your dataset will eventually be and then insert the data row-by-row.

import numpy as np

arr = np.zeros([4, 3])
print(arr)

Output

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

And then, you can add the data of row by row, and that is how you initialize the array and then append the value to the numpy array.

Conclusion

To create an empty numpy array, you can use np.empty() or np.zeros() function.

See also

Numpy array to list

Save numpy array

Numpy array attributes

How do you create an empty array in python?

If you want to learn how to create an empty list in Python efficiently, then this article is for you.

You will learn:

  • How to create an empty list using square brackets [].
  • How to create an empty list using list().
  • Their use cases.
  • How efficient they are (one is faster than the other!). We will use the timeit module to compare them.

Let's begin! ✨

🔹 Using Square Brackets

You can create an empty list with an empty pair of square brackets, like this:  

How do you create an empty array in python?

💡 Tip: We assign the empty list to a variable to use it later in our program.

For example:

num = []

The empty list will have length 0, as you can see right here:

>>> num = []
>>> len(num)
0

Empty lists are falsy values, which means that they evaluate to False in a boolean context:

>>> num = []
>>> bool(num)
False

Add Elements to an Empty List

You can add elements to an empty list using the methods append() and insert():

  • append() adds the element to the end of the list.
  • insert() adds the element at the particular index of the list that you choose.

Since lists can be either truthy or falsy values depending on whether they are empty or not when they are evaluated, you can use them in conditionals like this:

if num:
	print("This list is not empty")
else:
	print("This list is empty")

The output of this code is:

This list is empty

Because the list was empty, so it evaluates to False.

In general:

  • If the list is not empty, it evaluates to True, so the if clause is executed.
  • If the list is empty, it evaluates to False, so the else clause is executed.

Example:

In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, we add a sequence of elements (integers) to the list that was initially empty:

>>> num = []
>>> for i in range(3, 15, 2):
	num.append(i)

We check the value of the variable to see if the items were appended successfully and confirm that the list is not empty anymore:  

>>> num
[3, 5, 7, 9, 11, 13]

💡 Tip: We commonly use append() to add the first element to an empty list, but you can also add this element calling the insert() method with index 0:

>>> num = []
>>> num.insert(0, 1.5) # add the float 1.5 at index 0
>>> num
[1.5]

🔸 Using the list() Constructor

Alternatively, you can create an empty list with the type constructor list(), which creates a new list object.

According to the Python Documentation:

If no argument is given, the constructor creates a new empty list, [].
How do you create an empty array in python?

💡 Tip: This creates a new list object in memory and since we didn't pass any arguments to list(), an empty list will be created.

For example:

num = list()

This empty list will have length 0, as you can see right here:

>>> num = list()
>>> len(num)
0

And it is a falsy value when it is empty (it evaluates to False in a boolean context):

>>> num = list()
>>> bool(num)
False

Example:

This is a fully functional list, so we can add elements to it:

>>> num = list()
>>> for i in range(3, 15, 2):
	num.append(i)

And the result will be a non-empty list, as you can see right here:

>>> num
[3, 5, 7, 9, 11, 13]

🔹 Use Cases

  • We typically use list() to create lists from existing iterables such as strings, dictionaries, or tuples.
  • You will commonly see square brackets [] being used to create empty lists in Python because this syntax is more concise and faster.

🔸 Efficiency

Wait! I just told you that [] is faster than list()...

But how much faster?

Let's check their time efficiencies using the timeit module.

To use this module in your Python program, you need to import it:

>>> import timeit

Specifically, we will use the timeit function from this module, which you can call with this syntax:

How do you create an empty array in python?

💡 Tip: The code is repeated several times to reduce time differences that may arise from external factors such as other processes that might be running at that particular moment. This makes the results more reliable for comparison purposes.

🚦 On your marks... get set... ready! Here is the code and output:

First, we import the module.

>>> import timeit

Then, we start testing each syntax.

Testing []:

>>> timeit.timeit('[]', number=10**4)
0.0008467000000109692

Testing list():

>>> timeit.timeit('list()', number=10**4)
0.002867799999989984

💡 Tip: Notice that the code that you want to time has to be surrounded by single quotes '' or double quotes "". The time returned by the timeit function is expressed in seconds.

Compare these results:

  • []: 0.0008467000000109692
  • list(): 0.002867799999989984

You can see that [] is much faster than list(). There was a difference of approximately 0.002 seconds in this test:

>>> 0.002867799999989984 - 0.0008467000000109692
0.0020210999999790147

I'm sure that you must be asking this right now: Why is list() less efficient than [] if they do exactly the same thing?

Well... list() is slower because it requires looking up the name of the function, calling it, and then creating the list object in memory. In contrast, [] is like a "shortcut" that doesn't require so many intermediate steps to create the list in memory.

This time difference will not affect the performance of your program very much but it's nice to know which one is more efficient and how they work behind the scenes.

🔹 In Summary

You can create an empty list using an empty pair of square brackets [] or the type constructor list(), a built-in function that creates an empty list when no arguments are passed.

Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

I really hope that you liked my article and found it helpful. Now you can create empty lists in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️

If you want to dive deeper into lists, you may like to read:

  • Python List Append – How to Add an Element to an Array, Explained with Examples
  • The Python Sort List Array Method – Ascending and Descending Explained with Examples
  • Python List Append VS Python List Extend – The Difference Explained with Array Method Examples


Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do you create an empty array?

This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.

How do you create an array in Python?

In Python, you can create new datatypes, called arrays using the NumPy package. NumPy arrays are optimized for numerical analyses and contain only a single data type. You first import NumPy and then use the array() function to create an array. The array() function takes a list as an input.

Can you create an empty array in NumPy?

The empty() function is used to create a new array of given shape and type, without initializing entries. Shape of the empty array, e.g., (2, 3) or 2. Desired output data-type for the array, e.g, numpy. int8.

How do you create a blank 2D array in Python?

Create Empty Numpy array and append columns.
# Create an empty 2D numpy array with 4 rows and 0 column..
empty_array = np. empty((4, 0), int).
print('Empty 2D Numpy array:').
print(empty_array).