Modern OS allocate memory virtually, ie., memory is given to a process only when it is first used. zeros obtains memory from the operating system so that the OS zeroes it when it is first used. zeros_like on the other hand fills the alloced memory with zeros by itself. Both ways require about same amount of work --- it's just that with zeros_like the zeroing is done upfront, whereas zeros ends up doing it on the fly.

Technically, in C the difference is calling calloc vs. malloc+memset.

Answer from pv. on Stack Overflow
Top answer
1 of 2
27

Modern OS allocate memory virtually, ie., memory is given to a process only when it is first used. zeros obtains memory from the operating system so that the OS zeroes it when it is first used. zeros_like on the other hand fills the alloced memory with zeros by itself. Both ways require about same amount of work --- it's just that with zeros_like the zeroing is done upfront, whereas zeros ends up doing it on the fly.

Technically, in C the difference is calling calloc vs. malloc+memset.

2 of 2
25

My timings in Ipython are (with a simplier timeit interface):

In [57]: timeit np.zeros_like(x)
1 loops, best of 3: 420 ms per loop

In [58]: timeit np.zeros((12488, 7588, 3), np.uint8)
100000 loops, best of 3: 15.1 µs per loop

When I look at the code with IPython (np.zeros_like??) I see:

res = empty_like(a, dtype=dtype, order=order, subok=subok)
multiarray.copyto(res, 0, casting='unsafe')

while np.zeros is a blackbox - pure compiled code.

Timings for empty are:

In [63]: timeit np.empty_like(x)
100000 loops, best of 3: 13.6 µs per loop

In [64]: timeit np.empty((12488, 7588, 3), np.uint8)
100000 loops, best of 3: 14.9 µs per loop

So the extra time in zeros_like is in that copy.

In my tests, the difference in assignment times (x[]=1) is negligible.

My guess is that zeros, ones, empty are all early compiled creations. empty_like was added as a convenience, just drawing shape and type info from its input. zeros_like was written with more of an eye toward easy programming maintenance (reusing empty_like) than for speed.

np.ones and np.full also use the np.empty ... copyto sequence, and show similar timings.


https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/array_assign_scalar.c appears to be file that copies a scalar (such as 0) to an array. I don't see a use of memset.

https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/alloc.c has calls to malloc and calloc.

https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/ctors.c - source for zeros and empty. Both call PyArray_NewFromDescr_int, but one ends up using npy_alloc_cache_zero and the other npy_alloc_cache.

npy_alloc_cache in alloc.c calls alloc. npy_alloc_cache_zero calls npy_alloc_cache followed by a memset. Code in alloc.c is further confused with a THREAD option.

More on the calloc v malloc+memset difference at: Why malloc+memset is slower than calloc?

But with caching and garbage collection, I wonder whether the calloc/memset distinction applies.


This simple test with the memory_profile package supports the claim that zeros and empty allocate memory 'on-the-fly', while zeros_like allocates everything up front:

N = (1000, 1000) 
M = (slice(None, 500, None), slice(500, None, None))

Line #    Mem usage    Increment   Line Contents
================================================
     2   17.699 MiB    0.000 MiB   @profile
     3                             def test1(N, M):
     4   17.699 MiB    0.000 MiB       print(N, M)
     5   17.699 MiB    0.000 MiB       x = np.zeros(N)   # no memory jump
     6   17.699 MiB    0.000 MiB       y = np.empty(N)
     7   25.230 MiB    7.531 MiB       z = np.zeros_like(x) # initial jump
     8   29.098 MiB    3.867 MiB       x[M] = 1     # jump on usage
     9   32.965 MiB    3.867 MiB       y[M] = 1
    10   32.965 MiB    0.000 MiB       z[M] = 1
    11   32.965 MiB    0.000 MiB       return x,y,z
Discussions

np.zeros_like(a) is slower than np.zeros(shape=a.shape)
I was comparing the time about two ways of an array of zeros using np.zeros_like and np.zeros. I don't know if I'm missing something, but it seems that np.zeros_like is slower and, IMO, it ... More on github.com
🌐 github.com
October 23, 2017
Fill array with zeros like numpy does?
This is wrong because each row references the same array. If you change one value in the array, it will be changed for all rows. You should put the new double[3] statement directly inside the loop. Alternatively, if you're dealing with matrices, you should use n-dimensional arrays instead: - var bigDaddy = new double[1001, 3] this will create a 1001x3 matrix filled with zeroes by default - var bigDaddy = new double[3003] this will create a 3003 sized array filled with zeroes which you can then navigate with the % operator and use Span for operations for a performance boost More on reddit.com
🌐 r/csharp
20
0
October 31, 2024
numpy.empty equivalent in julia?
u = Array{T}(undef, shape_tuple) will do it More on reddit.com
🌐 r/Julia
19
4
October 27, 2020
Is it ever advantageous to use a standard Python list vs a numpy array when all elements are the same type?
very often it is more efficient to use a list of numpy arrays than a higher dimensional (3D, 4D, ...) array. E.g., if you are computing polynomials, storing the terms in a list of arrays will be approximately sqrt(n_terms) faster than an nd array with the term # on the first dimension. The numpy allocator is relatively better at many small arrays than it is a few jumbo ones. More on reddit.com
🌐 r/Python
13
4
December 8, 2020
People also ask

How is zeros_like different from zeros?
zeros_like takes an array template and inherits its shape and dtype by default. zeros takes the requested shape directly.
🌐
askpython.com
askpython.com › python-modules › numpy › numpy-zeros_like
NumPy zeros_like: Create a Zero Array from a Template - AskPython
How do I make zeros_like return floats?
Pass a floating-point dtype, such as dtype=np.float64, to override the input array's data type.
🌐
askpython.com
askpython.com › python-modules › numpy › numpy-zeros_like
NumPy zeros_like: Create a Zero Array from a Template - AskPython
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.5 Manual
full_like · Return a new array with shape of input filled with value. zeros · Return a new array setting values to zero. Examples · Try it in your browser! >>> import numpy as np >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=np.float64) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) Go BackOpen In Tab ·
🌐
AskPython
askpython.com › python-modules › numpy › numpy-zeros_like
NumPy zeros_like: Create a Zero Array from a Template - AskPython
October 4, 2026 - Import NumPy with the conventional np alias. Use zeros_like when an existing array should define the output shape and default data type.
🌐
Finxter
blog.finxter.com › home › learn python blog › np.zeros() — a simple illustrated guide
np.zeros() - A Simple Illustrated Guide - Be on the Right Side of Change
May 22, 2022 - Yes, as shown above, we can use either np.zeros or np.zeros_like to generate the same size all-zeros array. But you may notice that the data types of the output arrays are not the same. This is because we do not specify the dtype parameter in the first output, so it takes the default numpy.float64 data type.
🌐
w3resource
w3resource.com › numpy › array-creation › zeros_like.php
NumPy: numpy.zeros_like() function - w3resource
April 21, 2026 - Since b is a one-dimensional array of length 5, zeros_like(b) also creates a one-dimensional array of the same length, containing all zeros and having the same data type (float). ... Frequently asked questions (FAQ) - numpy.
Find elsewhere
🌐
YouTube
youtube.com › watch
Python: np.zeros vs np.zeros_like - YouTube
Descargar el Código: patreon.com/pythonmaratonJoin Patreon: patreon.com/pythonmaraton^Downloadable code & more! This tutorial shows the difference between np
Published: August 24, 2018
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.zeros.html
numpy.zeros — NumPy v2.3 Manual
zeros_like · Return an array of zeros with shape and type of input. empty · Return a new uninitialized array. ones · Return a new array setting values to one. full · Return a new array of given shape filled with value. Examples · Try it in your browser! >>> import numpy as np >>> np.zeros(5) array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=int) array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1)) array([[ 0.], [ 0.]]) >>> s = (2,2) >>> np.zeros(s) array([[ 0., 0.], [ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype array([(0, 0), (0, 0)], dtype=[('x', '<i4'), ('y', '<i4')]) Go BackOpen In Tab ·
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.6.dev0 Manual
full_like · Return a new array with shape of input filled with value. zeros · Return a new array setting values to zero. Examples · Try it in your browser! >>> import numpy as np >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=np.float64) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) Go BackOpen In Tab ·
🌐
GitHub
github.com › numpy › numpy › issues › 9909
np.zeros_like(a) is slower than np.zeros(shape=a.shape) · Issue #9909 · numpy/numpy · GitHub
October 23, 2017 - I don't know if I'm missing something, but it seems that np.zeros_like is slower and, IMO, it seems there is no reason to be... Test has been made using an Jupyter Notebook, and is shown below: import numpy as np; a=np.zeros(shape=(1000,1000)) %timeit -n100 np.zeros(shape=a.shape)
🌐
NumPy
numpy.org › doc › 1.25 › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v1.25 Manual
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)[source]# Return an array of zeros with the same shape and type as a given array. Parameters: aarray_like · The shape and data-type of a define these same attributes of the returned array. dtypedata-type, optional ·
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Create an array with the same value (np.zeros, np.ones, np.full) | note.nkmk.me
January 23, 2024 - To create an array filled with 0 that has the same shape and data type as another array, use np.zeros_like().
🌐
NumPy
numpy.org › doc › 2.4 › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.4 Manual
full_like · Return a new array with shape of input filled with value. zeros · Return a new array setting values to zero. Examples · Try it in your browser! >>> import numpy as np >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) Go BackOpen In Tab ·
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.1 Manual
full_like · Return a new array with shape of input filled with value. zeros · Return a new array setting values to zero. Examples · >>> import numpy as np >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) On this page
🌐
Kanaries
docs.kanaries.net › topics › NumPy › numpy-zeros
NumPy Zeros: Create Zero-Filled Arrays with np.zeros() – Kanaries
February 10, 2026 - Yes, np.zeros() is slightly faster ... allocate and then fill. For most practical purposes the difference is negligible. np.zeros() is the standard way to create zero-filled arrays in NumPy....
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.2 Manual
full_like · Return a new array with shape of input filled with value. zeros · Return a new array setting values to zero. Examples · >>> import numpy as np >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.]) On this page
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.zeros_like.html
numpy.zeros_like — NumPy v2.0 Manual
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None)[source]# Return an array of zeros with the same shape and type as a given array. Parameters: aarray_like · The shape and data-type of a define these same attributes of the returned array.
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-zeros_like-python
numpy.zeros_like() in Python - GeeksforGeeks
March 8, 2024 - This numpy method returns an array of given shape and type as given array, with zeros.
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_zeros_like_function.htm
Numpy zeros_like() Function
The Numpy zeros_like() function is used to create a new numpy array of the same shape and type as an existing array, but filled with zeros. This is particularly useful for initializing arrays of specific shapes without manually defining dimensions.
🌐
CASRAI
casrai.org › guides › research tools & software › statistical software for research › numpy zeros: np.zeros() syntax and examples
NumPy Zeros: np.zeros() Syntax and Examples — CASRAI
1 week ago - When you want an array with the same shape and type as one you already have, the documentation’s “See also” points to zeros_like. TypeError when passing dimensions as separate arguments. Tested on NumPy 2.5.1: np.zeros(2, 3) raised TypeError: Cannot interpret '3' as a data type, because the second positional argument is dtype.