How to Get a Python Number from a PyTorch Tensor with item()
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
tensor.item()
| Part | What it means |
|---|---|
tensor | A 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 numpyadds 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
import torch
score = torch.tensor([42])
print(score)
print(score.item())
print(type(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
uv run python item.py
tensor([42])
42
<class 'int'>
![The terminal after uv run python item.py: tensor([42]), then 42, then class int.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-item-02-output.webp)
The tensor prints as tensor([42]); item() gives the plain 42, a Python int. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
item() on a tensor with more than one value | RuntimeError: a Tensor with 2 elements cannot be converted to Scalar | tolist() for all the values, or pick one first: values[0].item() printed 1 |
| Comparing the tensor instead of its number | score > 40 printed tensor([True]), a tensor rather than True | score.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
- Tensor.item — PyTorch's reference for the method.
- Tensor.tolist — every value as a Python list.
- Tensors tutorial — PyTorch's introduction to tensors, including
item().
