0

Is it possible to add an element to the 'for' loop after the loop has started, so that the loop will include this element?

x = [object1, object2]

for object in x:
    if statement:
        x.append(object3)

or should i find a way in "while" loop?

Jacek
  • 17
  • 5
  • 1
    Does this answer your question? [Modifying list while iterating](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating) – BhusalC_Bipin Jun 14 '22 at 15:52

1 Answers1

0

I would probably go with something like this. But be aware whatever calculations you make to obtain 'object3' have to lead to a series with tendency towards the condition (Don't get trapped in the loop ;)

def iteration(x):
    object3 = x[-2] + x[-1]
    if object3 < 1000:
        x.append(object3)
        iteration(x)
    else:
        return x

x = [0, 1]
iteration(x)
print(x)
DataMuru
  • 16
  • 2