kame kame - 2 months ago 14
Python Question

Python: Change the parameter of the loop while the loop is running

I want to change a in the for-loop to [4,5,6].
This code just print: 1, 2, 3

a = [1,2,3]

for i in a:
global a
a = [4,5,6]
print i

I want the ouput
1, 4, 5, 6


You'll need to clarify the question because there is no explanation of how you should derive the desired output 1, 4, 5, 6 when your input is [1, 2, 3]. The following produces the desired output, but it's completely ad-hoc and makes no sense:

i = 0
a = [1, 2, 3]
while i < len(a):
    if a[i] == 1:
        a = [4, 5, 6]
        i = 0          # edit - good catch larsmans
        i += 1

The main point is that you can't modify the parameters of a for loop while the loop is executing. From the python documentation:

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

Edit: if based on the comments you are trying to walk URLs, you need more complicated logic to do a depth-first or breadth-first walk than just replacing one list (the top-level links) with another list (links in the first page). In your example you completely lose track of pages 2 and 3 after diving into page 1.