Using nested list comprehensions to create empty tensors with specific dimensions is unnecessarily complex and harder to understand than PyTorch’s
built-in alternatives.
When you write torch.tensor([[[] for _ in range(3)] for _ in range(5)])
, you’re creating a complex nested structure just to get an
empty tensor with shape (5, 3, 0)
. This approach has several drawbacks:
- Readability: The nested list comprehension syntax is verbose and requires mental parsing to understand the intended dimensions
- Maintainability: Changing dimensions requires modifying the list comprehension logic rather than simple numeric parameters
- Performance: Creating intermediate list structures before converting to tensors is less efficient than direct tensor
allocation
- Intent clarity: The code doesn’t clearly express that you want an empty tensor with specific dimensions
PyTorch provides torch.empty()
specifically for creating uninitialized tensors with given dimensions. This function is designed for
exactly this use case and makes your code more idiomatic.
What is the potential impact?
Using complex list comprehensions instead of torch.empty()
makes code harder to read and maintain. It can also impact performance due
to unnecessary intermediate list creation, especially when working with large tensor dimensions.
How to fix in PyTorch?
Replace the nested list comprehension with torch.empty()
, specifying the dimensions directly as arguments. The last dimension should
be 0 to create an empty tensor.
Non-compliant code example
import torch
# Complex list comprehension for empty tensor
empty_tensor = torch.tensor([[[] for _ in range(3)] for _ in range(5)]) # Noncompliant
Compliant code example
import torch
# Direct empty tensor creation
empty_tensor = torch.empty(5, 3, 0)
For dynamic dimensions, pass variables directly to torch.empty()
instead of using them in list comprehensions.
Non-compliant code example
import torch
a, b = 10, 5
results = torch.tensor([[[] for _ in range(b)] for _ in range(a)]) # Noncompliant
Compliant code example
import torch
a, b = 10, 5
results = torch.empty(a, b, 0)
Documentation