How to Create an Empty Tensor in Python using PyTorch


In this article, we show how to create an empty tensor in Pythong using the PyTorch library.

A tensor is one of the most basic building blocks of PyTorch. It is basically the equivalent of a numpy array.

According to pytorch's official website,, a tensor is a multi-dimensional matrix containing elements of a single data type.

The data type, referred to as the dtype of the tensor, can be a 16-bit floating point, 32-bit floating point, a 64-bit floating point, a 16-bit signed integer, a 32-bit signed integer, a 64-bit signed integer, a boolean, a quantized 4-bit unsigned integer, a quantized 8-bit unsigned integer, a quantized 8-bit signed integer, or a quantized 32-bit signed integer.

Also the tensors can take on different forms depending on whether you are using PyTorch with a CPU or GPU. This is referred to as CPU or GPU variants.

For this example code, though, we are not concerned with declaring tensor data types or CPU or GPU variants.

We simply go over how to create empty tensors.

This can be done with the empty() function.

This is shown in the code below.

So we create a variable, x, which we assign to, torch.empty(1)

This creates a one-dimensional tensor that contains one element.

The output for x is then shown, which is, tensor([0.])

We then create another variable, y, which we assign to, torch.empty(3)

This, again, creates a one-dimensional tensor, but this time consisting of 3 elements.

The output for y is then shown, which is, tensor([0., 0., 0.])

We then create another variable, z, which we assign to, torch.empty(2,3)

This creates a two-dimensional tensor, consisting of 2 groups of data each having 3 elements each.

The output for z is then shown, which is, tensor([[9.2755e-39, 1.0286e-38, 1.0653e-38], [2.9389e-39, 1.0286e-38, 9.0919e-39]])

So, as shown, when you are creating tensors with PyTorch, you do not need to immediately initialize the tensors with values. You can set them as empty to begin with and then later set the values.

And this is how to create an empty tensor in Python using PyTorch.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...