Skip to main content

How to Get a Python Number from a PyTorch Tensor with item()

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Many results in PyTorch are tensors holding a single number: a total, an average, a training loss. To print it plainly, compare it or store it, you want an ordinary Python number. item() gives you one. This guide uses it in PyTorch 2.15.0.

Syntax​

Syntax
tensor.item()
PartWhat it means
tensorA tensor with exactly one value, on any device
.item()Returns that value as a Python number: an int for whole numbers, a float for decimals (torch.tensor([7.5]).item() is a float)

PyTorch's reference says it "Returns the value of this tensor as a standard Python number. This only works for tensors with one element. For other cases, see tolist()."

The Example​

A script makes a tensor holding one score, then prints the tensor, the number item() takes out of it, and that number's type.

Prerequisites​

  • A uv project with PyTorch and NumPy. uv add torch numpy adds both; without NumPy, PyTorch 2.15.0 prints a warning each time it starts. This guide uses PyTorch 2.15.0 and NumPy 2.5.5 on Python 3.15.2, with uv 0.13.10, on an Apple M1 Pro.

Step 1: Write the Script​

item.py
import torch

score = torch.tensor([42])
print(score)
print(score.item())
print(type(score.item()))

The item.py script in a macOS-style code window: a tensor holding 42, then prints of the tensor, score.item() and the type of score.item().

score is a tensor with one value. The last two lines print what item() returns and what kind of object it is.

Step 2: Run It​

Terminal
uv run python item.py
Output
tensor([42])
42
<class 'int'>

The terminal after uv run python item.py: tensor([42]), then 42, then class int.

The tensor prints as tensor([42]); item() gives the plain 42, a Python int. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
item() on a tensor with more than one valueRuntimeError: a Tensor with 2 elements cannot be converted to Scalartolist() for all the values, or pick one first: values[0].item() printed 1
Comparing the tensor instead of its numberscore > 40 printed tensor([True]), a tensor rather than Truescore.item() > 40, which printed True

FAQ​

Does item() work on a tensor on the GPU?​

Yes. A one-value tensor made on the M1 Pro's GPU, mps:0, gave 7.5 with item(), with no .cpu() first.

How do I get all the values of a bigger tensor?​

With tolist(), as How to Turn a PyTorch Tensor into a Python List with tolist() shows.

Conclusion​

score.item() turned the one-value tensor tensor([42]) into the Python int 42, and the same call worked on a tensor on the GPU. On a tensor with more values, it raised a RuntimeError.

Additional Resources​