PyTorch tensor is a multidimensional array designed for complex numerical calculations that can run on GPU or CPU, whereas Python integer is a basic data type used for general-purpose programming.
1D tensor is a vector that contains a single or multiple elements. If a tensor holds a single value, it is more convenient to convert it into a basic integer.
Single-Element 1D Tensor
If our input 1D tensor has a single element, use the .item() method to extract the scalar value as a Python integer.

import torch tensor = torch.tensor([21], dtype=torch.int32) print(tensor) # Output: tensor([21], dtype=torch.int32) print(type(tensor)) # Output: <class 'torch.Tensor'> # Extracting integer from tensor using .item() method value = tensor.item() print(value) # Output: 21 print(type(value)) # Output: <class 'int'>
The above output shows that we got the scalar value 21 in the output. This approach works for tensors on any device (CPU/GPU) and with requires_grad=True.
Multi-Element 1D Tensor
If the tensor has multiple elements, you can do one of the following things:
- Extract a specific element (e.g., the first or last).
- Convert the entire tensor to a list of integers.
Extracting a Specific Element
To extract an element at a specific position, pass its index while accessing a tensor and then apply the .item() method to it.

import torch tensor = torch.tensor([21, 11, 19, 18], dtype=torch.int32) # Extracting first and last element first_element = tensor[0].item() last_element = tensor[3].item() print(first_element) # Output: 21 print(last_element) # Output: 18
Converting the entire tensor to a list of integers
PyTorch provides a .tolist() function that will convert the tensor into a list.
import torch tensor = torch.tensor([21, 11, 19, 18], dtype=torch.int32) # Converting to list of integers int_list = tensor.tolist() print(int_list) # Output: [21, 11, 19, 18]
Empty Tensor
If the input tensor is empty and you try to extract the integer using the .item() method, it will throw the RuntimeError: a Tensor with 0 elements cannot be converted to Scalar exception.
To fix the RuntimeError: a Tensor with 0 elements cannot be converted to Scalar exception, check if the tensor is empty using the .numel() method.
import torch tensor = torch.tensor([], dtype=torch.int32) # Check if the tensor is empty if tensor.numel() == 0: print("Tensor is empty!") # Output: Tensor is empty! else: # Safe to call only if tensor has one element value = tensor.item() int_list = tensor.tolist() print(int_list) # Output: []
Non-Integer Tensor
If your input tensor is not an IntTensor, let’s say a FloatTensor, you need to convert it to IntTensor first using the .int() method.
import torch tensor = torch.tensor([1.9], dtype=torch.float32) value = tensor.int().item() print(value) # Output: 1 (truncates decimals)
The output is an integer 1, which means the int() function truncates decimals completely.
Use .to(torch.int32) or .int() to ensure integer dtype.