Index sequences
Generate integer indices for tensor operations or iteration.
PyTorch · Function
Creates a 1-D tensor containing values from start up to, but excluding, end, separated by step. start defaults to 0 and step to 1; dtype is inferred unless specified.
torch.arange returns a one-dimensional tensor whose values begin at start and advance by step while remaining below end. The result size is determined by the interval and step, and omitted start or step values default to 0 and 1 respectively.
torch.arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor| Name | Type | Description |
|---|---|---|
start | Number, optional | Starting value of the sequence; defaults to 0. |
end | Number | Exclusive upper endpoint of the sequence. |
step | Number, optional | Difference between adjacent values; defaults to 1. |
out | Tensor, optional | Optional destination tensor. |
dtype | torch.dtype, optional | Desired dtype; if omitted, PyTorch infers it from the inputs. |
layout | torch.layout, optional | Desired tensor layout; defaults to torch.strided. |
device | torch.device, optional | Device on which to create the tensor. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to false. |
A one-dimensional Tensor containing the generated range.
import torch
steps = torch.arange(0, 10, 2, dtype=torch.float32)
print(steps) # tensor([0., 2., 4., 6., 8.])Creates floating-point values starting at 0, advancing by 2, and stopping before 10.
Generate integer indices for tensor operations or iteration.
Build regularly spaced numeric coordinates with a chosen increment.
Create a range directly on a selected device and with a chosen dtype.
It creates a one-dimensional tensor containing values in the half-open interval [start, end), separated by step. The number of elements is the ceiling of (end - start) divided by step.
Follow-up: What happens when start is omitted? start defaults to 0, so torch.arange(end) generates values from 0 up to, but excluding, end.
The required argument is end; start defaults to 0 and step defaults to 1. Thus torch.arange(5) produces integer values 0 through 4.
Follow-up: How can the output type be controlled? Pass dtype explicitly, such as dtype=torch.float32.
If dtype is omitted, PyTorch infers it from the inputs: floating-point inputs use the default floating-point dtype, while otherwise the result defaults to torch.int64. The function also accepts device, layout, out, and requires_grad keyword arguments.
Follow-up: Why should dtype often be explicit for fractional ranges? Floating-point inference depends on the configured default dtype, so explicit dtype makes the result predictable.
torch.linspacetorch.zerostorch.onestorch.tensor