You can use the generator expression:
cubed = (x ** 3 for x in range(1, 11)) cube4 = [c for c in cubed if c % 4 == 0]
This is still repeated through range() only once, but now the expression x ** 3 evaluated only once when the generator expression is repeated. You can combine it in one line:
cube4 = [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0]
but keeping the generator expression on a separate line can help in understanding (no pun intended).
Demo:
>>> [c for c in (x ** 3 for x in range(1, 11)) if c % 4 == 0] [8, 64, 216, 512, 1000]
Of course, mathematically speaking, for your simple example, you could just use [x ** 3 for x in range(2, 11, 2)] , but I suspect that this was not quite the purpose of your question .:-)
source share