Q:

python for loop reiterate

I have a really simple python problem but it does not seem that simple. I am performing a database query however it boils down to the principle below.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)
    fruits = ["1", "2", "3"]
    print(fruits)

How do I get x to change to the new values?
Current output for x is "apple", "banana", "cherry" however after I change fruit I would like "apple", "1", "2", "3"

A:

If I undestand your question correctly, then you DON'T change collection while you iterate through it.
What you can do is to iterate over range of indexes and then you can change collection. Like:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(fruits[i])
    fruits = ["1", "2", "3"]
    print(fruits)

But be careful with index out of range if your fruits length changes. The safest way would be to use while loop:
fruits = ["apple", "banana", "cherry"]
i = 0;
while i < len(fruits):
    print(fruits[i])
    fruits = ["1", "2", "3"]
    print(fruits)
    i += 1

If you want to completely reset iterations in same loop, which is very strange scenario, but you can do:
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
    print(fruits[i])
    newFruits = ["1", "2", "3"]
    if newFruits != fruits:
        i = -1
        fruits = newFruits
    print(fruits)
    i += 1

Mind that this code is inefficient, cause:

You assign new array on each iteration, which can cause a memory leak.
Comparing arrays is O(n) complexity operation.

For better code, more information about the problem is needed.

