0

I'm currently building an image pixel iterator, and I'm picking a point on the 2D grid and iterating outwards (up, down, left, right, etc...). As I was developing, I wrote a for-loop like this to see how it would function:

expanding = [1, 2]
# Expected functionality: continues to iterate "3" forever.
for expand in expanding:
  expanding.append(3)

I would expect this to continue in an infinite loop, with the iterating sequence looking like: 1, 2, 3, 3, 3, 3,... so forth. Though it only seems to close on 2 due to the structure of my outputs.

This part of my algorithm is tasked with breaking an image into its colour groups by picking random coordinates and expanding outwards, checking if the colour range is too far out of the parent colour, hence the requirement of a continuous iterator till it finalizes at nothing.

The use would be being able to simply append to the array for it to be iterated in the future, without needing to finish the array and remove specific elements before continuing, as a "live for loop".

Jack Hales
  • 1,574
  • 23
  • 51

3 Answers3

1

I've just tried this myself by using the 'enumerate' method to wrap the list and below code does what you're asking:

my_list = [1,2]

for i, element in enumerate(my_list):
   my_list.append(3)
Michael
  • 153
  • 1
  • 9
1

Here's a post talking about the reasons not to change the container you're iterating over, even though you can.

How about using a while loop and breaking out when your done instead:

my_list = [1,2]

while True:
    my_list.append(3)
    if #(check if out of range):
        break
cwalvoort
  • 1,851
  • 1
  • 18
  • 19
1

You might want to look at another data structure for this, like a queue or stack.

As a very very poor example, there are graph algorithms that are not too far from the logic below:

seen = set()
stack = [1]
while stack:
    current = stack.pop()
    if current in seen or abs(current) > 5:
        continue
    seen.add(current)
    print 'Processed %s' % current
    stack.append(current + 1)
    stack.append(current - 1)

would provide

Processed 1
Processed 0
Processed -1
Processed -2
Processed -3
Processed -4
Processed -5
Processed 2
Processed 3
Processed 4
Processed 5
Cireo
  • 4,197
  • 1
  • 19
  • 24