PyTorch torch.arange() method is “used to create a 1-dimensional tensor with a sequence of numbers.” This method is similar to Python’s built-in range() but returns a tensor.
Syntax
torch.arange(start=0, end, step=1, *, out=None, dtype=None,
layout=torch.strided, device=None, requires_grad=False)
Parameters
- start (Number): It is the starting value for the set of points. Default: 0.
- end (Number): It is the ending value for the set of points
- step (Number): It is the gap between each pair of adjacent points. Default: 1.
- out: An output tensor.
- dtype: The desired data type of the tensor. Default is inferred.
- layout: Memory layout of the tensor. The default is the torch.strided.
- device: The desired device for the tensor. Default is the current default device.
- requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.
Example 1: Creating a Tensor with Numbers from 0 to 4
import torch
tensor1 = torch.arange(5)
print(tensor1)
Output
tensor([0, 1, 2, 3, 4])
Example 2: Creating a Tensor with Numbers from 2 to 8 in Steps 2
import torch
tensor2 = torch.arange(2, 10, 2)
print(tensor2)
Output
tensor([2, 4, 6, 8])
Example 3: Creating a Tensor with Numbers from 0 to 1 in Steps of 0.1
import torch
tensor3 = torch.arange(0, 1.1, 0.1)
print(tensor3)
Output
tensor([0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000,
0.9000, 1.0000])
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.