Retrieve Tensor as scalar value with `` not working

This question refers to latest version in master branch.

When we define a Tensor object, what is the best way to retrieve one of element as scalar value ?

x = torch.Tensor([2, 3])
  •[0] still returns Tensor type

  • x.numpy()[0] gives scalar value, but with type numpy.int64 which sometimes leads to problems

  • x.tolist()[0] returns int type.

Seems for now tolist() works well. The question is, why does not return int type ?



If you want to get the value as a python number, you can use the .item() method: x[0].item() in your example.


Cool ! Thanks for the help. btw, is item() documented already ? I cannot manage to find it here

Doesn’t look like so idd.
This is weird, because it is actually listed in the code doc here not sure what happened here :confused:
@smth is that a doc generation issue? Or something I’m missing here with the doc?

Thanks for pointing that out. We need to add it to docs/source/tensors.rst as well.

1 Like

Made a PR already.