Sorry for what seems like a basic question, but I could not find it anywhere. In Python 2, I would like to apply a 1-variable function to its own output storing the list of all steps, i.e. if f(x) returns x*x then iterating from 2, i need to get
[2, 4, 16, 256, 65536, ...]
Ideally, I would need to pass in my function f
, the first input 1
, and the number of iterations I would like to keep.
I guess this is, in some sense, the opposite of reduce
and somewhat similar to unfold
from functional programming.
A naive way to do this is to write
out = [2]
for x in xrange(5):
out.append(f(out[-1]))
What is a good Pythonic way to do this? Thank you very much.
What you need is a "Generator". For example,
def f(x, n):
for _ in range(n):
yield x
x = x * x
l = list(f(2, 5))
print(l) # [2, 4, 16, 256, 65536]
Or
def f(x):
while True:
yield x
x = x * x
for v in f(2):
if v > 100000:
break
print(v), # 2 4 16 256 65536