How to Convert a Tuple to a PyTorch Tensor in Python

 A tuple in Python is a data structure that stores the data in a sequence and is immutable. A PyTorch tensor is like a NumPy array but the computations on tensors can utilize the GPUs whereas the numpy array can't.

To convert a tuple to a PyTorch Tensor, we use  torch.tensor(tuple) . It takes a tuple as input and returns a PyTorch tensor.

Python 3 example 1.

import torch
tpl = (1,2,3,4,5# a tuple with 5 values
print("Tuple:", tpl)
tens = torch.tensor(tpl) # tuple converted to pytorch tensor
print("Tensor:", tens)


Tuple: (1, 2, 3, 4, 5) Tensor: tensor([1, 2, 3, 4, 5])