I want to replace and optimize an extensively used while-loop that generates list values from an input list. How can this be accomplished with iter, itertools, a generator function or something else? The following example code is for illustration only:
thislist = [2, 8, 17, 5, 41, 77, 3, 11]
newlist = []
index = 0
listlength = len(thislist)
while index < listlength:
value = 0
while thislist[index] >= 0:
value += thislist[index]
value += 2 * value
index += 1
value += thislist[index]
index += 1
newlist.append(value)
print newlist
You can do it with a generator. It yields the next value every time you call “next” on it.