๐ŸŽ“ A1Learner
๐Ÿ”

PyTorch Tensors to Python Values

.item() turns a one-value tensor into a plain Python number. .tolist() turns a whole tensor into plain Python lists.

Printing is not the value

The print shows the tensor display with its wrapper. .item() gives the plain number inside.

import torch

answer = torch.tensor(42)
print(answer)
print(answer.item())

Turn a tensor into a list

.tolist() builds plain Python lists from the tensor's values. The type print proves the result is a list.

row = torch.tensor([1, 2, 3])
values = row.tolist()
print(values)
print(type(values).__name__)

Read one computed value

A sum is a one-value tensor. .item() reads its value as a Python float.

total = torch.tensor([10.0, 20.0, 30.0]).sum()
print(total.item())

Example

import torch

scores = torch.tensor([80.0, 90.0, 75.0, 85.0])
average = scores.mean()
value = average.item()
print("Tensor average:", average)
print(f"Average: {value:.1f}")
print("Type:", type(value).__name__)

Key points

  • Use .item() to read the single value out of a one-value tensor
  • Use .tolist() to turn a whole tensor into Python lists
  • Printing a tensor shows a display with a tensor wrapper, not a plain value
  • .item() returns an int for a whole-number tensor and a float for a decimal tensor
  • Plain Python values work with normal Python tools, like string formatting
  • In short, .item() and .tolist() copy the values out of the tensor into Python

In this example, scores holds four test scores. mean() averages them into a one-value tensor. .item() pulls the average out as a plain Python float. The first print shows the tensor with its wrapper. The second print formats the plain float to one decimal place. The last print shows the value's type is float.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Python Playground

Exercise

Which method reads the single value from a one-value tensor as a Python number?