Here are three ways to get the index of a specific value in PyTorch Tensors.
- Using PyTorch’s where()
- Using Numpy’s where()
- Using Python’s index()
Method 1: Using PyTorch’s where()
PyTorch’s where() function returns a tuple of indices where a given condition is true.
To find the index of a specific value, you can use PyTorch’s where() function.
import torch
tensor = torch.tensor([11, 19, 21, 46, 52])
value = 21
indices = torch.where(tensor == value)[0]
print(indices.item())
Output
2
Method 2: Using Numpy’s where()
PyTorch tensors can easily be converted to numpy arrays using the .numpy() method. Once it’s a numpy array, you can use numpy’s where() function to get the index.
import torch
import numpy as np
tensor = torch.tensor([11, 19, 21, 46, 52])
value = 21
index = np.where(tensor.numpy() == value)[0]
print(index)
Output
[2]
Method 3: Using Python’s index() function
You can convert the PyTorch tensor to a Python list and then use the index() method of the list to get the index. This method may not be as efficient for larger tensors but is straightforward for smaller ones.
import torch
tensor = torch.tensor([11, 19, 21, 46, 52])
value = 21
index = tensor.tolist().index(value)
print(index)
Output
2
Conclusion
The best and easiest way to get the index of a specific value in PyTorch is to use PyTorch’s where() method. If you are working solely within the PyTorch ecosystem (especially with larger tensors), use PyTorch’s where().
PyTorch’s where() method is typically faster than the other methods for large tensors since it’s GPU-accelerated if you’re using a CUDA tensor.
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.