Reputation: 10795
I have a list containing values (tuples in my case) - in the beginning there is 1 element. I need to loop over a list and for the last value in the list apply some computations, which will provide me with the next list element. After that I need to concatenate those lists and using the last value of the list compute next element. And so on...
How can it be done? NumPy also can be used.
Now I do like this, but it does not work
while True:
lst = [1]
print(lst)
for i in range(len(lst)):
elem = lst[-1]
new = elem + 10 // dummy computations
lst.append(new)
Upvotes: 2
Views: 4225
Reputation: 46530
If you just want to loop through the list later, you can build a generator:
def f(elem):
return elem + 10
def lst(init):
yield init
while True:
next = f(init)
yield next
init = next
This goes on forever, so be sure your loop has some break in it:
for i in lst(1):
print i
if i > 100:
break
prints:
1
11
21
31
41
51
61
71
81
91
101
Upvotes: 3
Reputation: 64308
How is this for a start?
def f(x):
return 2*x+1
a = [ 1 ]
while len(a) < 8:
x = a[-1]
y = f(x)
a.append(y)
a
=> [1, 3, 7, 15, 31, 63, 127, 255]
Upvotes: 2