Creating a torch tensor from a generator
I attempt to construct a tensor from a generator as follows:

&gt;&gt;&gt; torch.tensor(i**2 for i in range(10))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
RuntimeError: Could not infer dtype of generator


Currently I just do:

&gt;&gt;&gt; torch.tensor([i**2 for i in range(10)])
tensor([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])


Is there a way to avoid needing this intermediate list?

As @blue-phoenox already points out, it is preferred to use the built-in PyTorch functions to create the tensor directly. But if you have to deal with generator, it can be advisable to use numpy as a intermediate stage. Since PyTorch avoid to copy the numpy array, it should be quite performat (compared to the simple list comprehension)

&gt;&gt;&gt; import torch
&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; torch.from_numpy(np.fromiter((i**2 for i in range(10)), int))
tensor([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])

