How to Convert Python List to PyTorch Tensor

Here are two ways to convert Python List to PyTorch Tensor:

  1. Using torch.tensor()
  2. 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

PyTorch Tensor to Python List

Leave a Comment