Create Tensor from List
Problem Statement
Create a PyTorch tensor from a nested Python list.
Background
Tensors are the fundamental data structure in PyTorch. They are similar to NumPy arrays but can run on GPUs. Creating tensors from Python lists is the most basic operation.
Your Task
Write a function create_tensor(data) that takes a nested Python list and returns a PyTorch tensor.
Output Format
Your function must return a PyTorch tensor. The test will convert it to a nested list for comparison.
Example:
[[1, 2], [3, 4]]
tensor([[1, 2],
[3, 4]])We use torch.tensor() to convert a Python list directly into a PyTorch tensor
Constraints:
- Input will always be a valid nested list of numbers
- The inner lists will all have the same length
- Values will be integers between -1000 and 1000
1. Background Knowledge
PyTorch tensors are multi-dimensional arrays analogous to NumPy arrays but with GPU acceleration and autograd support for deep learning. They serve as the core data structure for representing data, model parameters, and computation graphs in PyTorch. Tensors generalize scalars (0D), vectors (1D), matrices (2D), and higher-dimensional arrays, enabling efficient operations like element-wise arithmetic, matrix multiplication, and convolutions.
Key prerequisites:
- Nested lists: Python lists can represent multi-dimensional data (e.g., [[1,2],[3,4]] for a 2x2 matrix).
- Data types: Input integers map to torch.int64 (long) by default; constraints ensure valid numeric data.
- Conversion mechanism: PyTorch's torch.tensor() constructor recursively interprets nested lists as tensors, inferring shape and dtype.
No seminal diagrams directly apply (e.g., from Paszke et al.), but tensor creation is foundational before advanced tensor networks.
2. Algorithm Approach
The standard technique is direct constructor invocation: torch.tensor(data). This performs recursive parsing:
- Flatten nested structure into a contiguous buffer.
- Infer shape from list dimensions.
- Allocate tensor memory (CPU by default; GPU via device).
Pseudocode:
function create_tensor(data):
return torch.tensor(data) # Handles arbitrary nesting
For visualization, tensor construction mirrors array initialization in PyTorch's eager execution model:
List → Buffer allocation → Shape inference → Tensor object
No flowchart needed; it's a single API call. Alternatives like torch.as_tensor() avoid copying if input is already array-like, but torch.tensor() copies for safety with lists.
3. Step-by-Step Strategy
- Import PyTorch: import torch.
- Define function: def create_tensor(data):.
- Convert: return torch.tensor(data).
- Handle output: Tests use .tolist() for comparison, preserving structure.
Complete solution:
import torch
def create_tensor(data):
return torch.tensor(data)
Verification:
data = [[1, 2], [3, 4]]
tensor = create_tensor(data)
print(tensor.tolist()) # [[1, 2], [3, 4]]
print(tensor.shape) # torch.Size([2, 2])
print(tensor.dtype) # torch.int64
This works for any valid nested list per constraints (uniform inner lengths, integers).
4. Common Pitfalls
- Missing import: NameError: name 'torch' is not defined.
- Using NumPy: np.array(data) returns NumPy array; convert via torch.from_numpy() but torch.tensor() is simpler for lists.
- Device mismatch: Default is CPU; add device='cuda' only if needed (not required here).
- dtype issues: Lists auto-infer int64; explicit torch.tensor(data, dtype=torch.float32) if floats needed.
- Mutable inputs: torch.tensor() copies data, avoiding side effects.
- Irregular nesting: Constraints guarantee uniformity; no need for manual reshaping.
- GPU without check: Avoid torch.tensor(data).cuda() unless torch.cuda.is_available().
5. Time & Space Complexity
- Time: O(n), where n is total elements. Recursive parsing and buffer copy are linear in data size.
- Space: O(n) for tensor storage (matches input size) + temporary O(d) stack for depth d (negligible).
Edge cases:
| Case | Elements n | Time | Space | Notes |
|---|---|---|---|---|
| Scalar | 1 | O(1) | O(1) | 0D tensor |
| 1D [1,2,3] | 3 | O(3) | O(3) | Shape |
| 2D [[1,2],[3,4]] | 4 | O(4) | O(4) | Shape [2,2] |
| Deep nest (e.g., 10x10) | 100 | O(100) | O(100) | Constraints ensure validity |
This scales efficiently for constraints (values -1000 to 1000, uniform shapes).