torch.Tensor.tolist: How to Convert PyTorch Tensor to Python List

To convert PyTorch Tensor to Python List, you can “use the torch.Tensor.tolist() method.”

The torch.Tensor.tolist() method “returns the tensor as a (nested) list.” For scalars, a standard Python number is returned, just like with item(). Tensors are automatically moved to the CPU first if necessary.

import torch

# Create a PyTorch tensor
tensor = torch.Tensor([[1, 2], [3, 4]])

python_list = tensor.tolist()

print("Tensor:")
print(tensor)

print("Python List:")
print(python_list)

Output

How to Convert PyTorch Tensor to Python List

That’s it!

Related posts

Python List to PyTorch Tensor

Leave a Comment