Here are two ways to convert Python List to PyTorch Tensor:
- Using torch.tensor()
- Using torch.Tensor()
Method 1: Using torch.tensor()
PyTorch torch.Tensor() method is “used to create a tensor with the same dtype as the input data.” This is more flexible but can be a source of surprises if you’re not careful about the data types in your list.
import torch
# Using torch.tensor()
list_data = [[1, 2], [3, 4]]
tensor_from_list = torch.tensor(list_data)
print("Using torch.tensor():", tensor_from_list)
Output
Using torch.tensor(): tensor([[1, 2],
[3, 4]])
Method 2: Using torch.Tensor()
PyTorch torch.Tensor() method is “used to create a tensor with the default float dtype (torch.float32).”
import torch
# Using torch.Tensor()
list_data = [[1, 2], [3, 4]]
tensor_from_list2 = torch.Tensor(list_data)
print("Using torch.Tensor():", tensor_from_list2)
Output
Using torch.Tensor(): tensor([[1., 2.],
[3., 4.]])
That’s it!
Related posts

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.