# How Pytorch Tensor get the index of specific value

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How Pytorch Tensor get the index of specific value in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

## How Pytorch Tensor get the index of specific value?

1. How Pytorch Tensor get the index of specific value?

I think there is no direct translation from `list.index()` to a pytorch function. However, you can achieve similar results using `tensor==number` and then the `nonzero()` function. For example:

2. Pytorch Tensor get the index of specific value

I think there is no direct translation from `list.index()` to a pytorch function. However, you can achieve similar results using `tensor==number` and then the `nonzero()` function. For example:

## Method 1

I think there is no direct translation from `list.index()` to a pytorch function. However, you can achieve similar results using `tensor==number` and then the `nonzero()` function. For example:

```t = torch.Tensor([1, 2, 3])
print ((t == 2).nonzero(as_tuple=True)[0])
```

This piece of code returns

1

[torch.LongTensor of size 1×1]

## Method 2

For multidimensional tensors you can do:

```(tensor == target_value).nonzero(as_tuple=True)
```

The resulting tensor will be of shape `number_of_matches x tensor_dimension`. For example, say `tensor` is a `3 x 4` tensor (that means the dimension is 2), the result will be a 2D-tensor with the indexes for the matches in the rows.

```tensor = torch.Tensor([[1, 2, 2, 7], [3, 1, 2, 4], [3, 1, 9, 4]])
(tensor == 2).nonzero(as_tuple=False)
>>> tensor([[0, 1],
[0, 2],
[1, 2]])```

## Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read