MrJoe
MrJoe

Reputation: 445

Creating an infinite for loop

I wanted to test if python would let me run this code:

listWords = []
for i in range (len(listWords)+1):
    listWords.append("New word")
print ("End loop")

The reason being I want to create a programme that tries to solve a solution and then adds new items to a list for testing.

Why does python NOT update the for loop range when I add a new item to the list?

Is there any way around this using a for loop? (I suspect a while loop will do for my case, but I am just curious)

Thanks

Upvotes: 1

Views: 75

Answers (2)

tobias_k
tobias_k

Reputation: 82899

As already noted, updating a list while iterating it is generally a bad idea. However, it seems like in this case this is exactly what you want to do. Instead of calculating the len of the list before iterating the list (which is exactly why it is never updated) you could iterate the elements in the list directly.

>>> lst = [1,2,3]
>>> for x in lst:
...     if x < 10:
...         lst.append(x*2)
...         
>>> lst
[1, 2, 3, 2, 4, 6, 4, 8, 12, 8, 16, 16]

If you need the index of the current element (or both the index and the element itself) you could use for i, x in enumerate(lst) to the same effect.

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Iterating over a list which you are simultaneously updating is bad practice.

In your code, the range is already calculated before you run the loop, so the range will be range(1), and then the for loop runs just that once and stops. This can also be observed if listWords is not empty, but is listWords = ['a','b'], so below loop run 3 times since the iterator is range(3)

Then the code becomes.

listWords = ['a','b']
for i in range (len(listWords)+1):
    listWords.append("New word")
print ("End loop")
print(listWords)
['a', 'b', 'New word', 'New word', 'New word']

While loop doesn't have such a limitation, The below example will keep running since len(listWords) is always updated at the end of next iteration

listWords = []
i = 0
while i <  (len(listWords)+1):
    listWords.append("New word")
    i+=1

Upvotes: 2

Related Questions