Depending on your problem, a good โpythonicโ way to deal with such a structure may be to abstract it into a generator. For your trivial example:
def squares(): for x in range(0,10): y = x*x yield y
Then:
temp_list = [i for i in squares()]
Very often, when you need such a temporary list, because you are performing a series of operations on your data, each of which is associated with a different cycle. Using generators instead can significantly improve performance and memory usage, as they result in only one cycle.
Note that for trivial examples it is usually easier to write a generator expression:
temp_list = (x*x for x in range(0, 10))
If you need a not-very-pythonic way to do this, you can edit the locals dictionary, but this is not a good idea, as this leads to obfuscation of the code:
for x in range(0, 10): y = x*x locals().setdefault('temp_list', []).append(y)
source share