How to Create Tensor from List in PyTorch: Simple Guide
To create a tensor from a list in PyTorch, use
torch.tensor() and pass your list as the argument. This converts the list into a PyTorch tensor that you can use for machine learning tasks.Syntax
The basic syntax to create a tensor from a list in PyTorch is:
torch.tensor(data, dtype=None, device=None)
Here, data is your Python list or nested lists. dtype is optional and sets the data type (like float or int). device is optional and sets where the tensor lives (CPU or GPU).
python
import torch # Create a tensor from a simple list my_list = [1, 2, 3] tensor = torch.tensor(my_list) print(tensor)
Output
tensor([1, 2, 3])
Example
This example shows how to create a 2D tensor from a nested list and specify the data type as float.
python
import torch nested_list = [[1, 2], [3, 4]] tensor_2d = torch.tensor(nested_list, dtype=torch.float32) print(tensor_2d) print('Shape:', tensor_2d.shape) print('Data type:', tensor_2d.dtype)
Output
tensor([[1., 2.],
[3., 4.]])
Shape: torch.Size([2, 2])
Data type: torch.float32
Common Pitfalls
Common mistakes when creating tensors from lists include:
- Passing lists with mixed data types, which can cause unexpected tensor types.
- Not specifying
dtypewhen you need a specific type, leading to default types that may not fit your needs. - Trying to create tensors from irregular nested lists (lists of different lengths), which will raise errors.
Example of wrong and right ways:
python
import torch # Wrong: irregular nested list try: bad_list = [[1, 2], [3]] bad_tensor = torch.tensor(bad_list) except Exception as e: print('Error:', e) # Right: regular nested list good_list = [[1, 2], [3, 4]] good_tensor = torch.tensor(good_list) print(good_tensor)
Output
Error: expected sequence of length 2 at dim 1 (got 1)
tensor([[1, 2],
[3, 4]])
Quick Reference
Tips for creating tensors from lists in PyTorch:
- Use
torch.tensor()to convert lists to tensors. - Specify
dtypeto control the tensor's data type. - Ensure nested lists are regular (all inner lists have the same length).
- Use
deviceto place tensors on CPU or GPU.
Key Takeaways
Use torch.tensor() to convert Python lists into PyTorch tensors easily.
Specify dtype to control the data type of the tensor for your needs.
Nested lists must be regular; irregular shapes cause errors.
You can place tensors on CPU or GPU by setting the device parameter.
Always check tensor shape and type after creation to avoid bugs.