Shaun Han
Shaun Han

Reputation: 2777

how to loop through a list where the items of the list are constantly appended in the loop?

I am new to Python. I want to write a search algorithm that can achieve the following: given a point → search a nearby point that satisfies a certain condition → use that new point to search for the next nearby new point → repeat this until no nearby new point can be found. This is my script, the new_point_near_this_point() is a self-defined function that returns boolean value of whether there is a nearby point satisfying a condition or not. init_point is the starting point.

lst = [init_point]
for i in lst[-1]:
    if new_point_near_this_point(i):
        lst.append(new_point)
    else:
        break

However, this doesn't work since it will only loop through a single initial point. I want to know how can I implement a search algorithm that can loop through a list where the items of the list are constantly appended (once per iteration) in the loop?

Upvotes: 0

Views: 78

Answers (2)

trincot
trincot

Reputation: 350770

You should change new_point_near_this_point so that it does not just return a boolean, but the nearby point that was found. Otherwise you have no way to progress to the next point.

So assuming that a point is returned by new_point_near_this_point when there is one (or None otherwise), you could do it like this:

list = []
point = init_point
while point:
    list.append(point)
    point = new_point_near_this_point(point)

Upvotes: 1

Kelly Bundy
Kelly Bundy

Reputation: 27629

With the same assumption as @trincot, that new_point_near_this_point returns a true new point or a false value if there isn't one:

lst = [init_point]
for point in lst:
    if new_point := new_point_near_this_point(point):
        lst.append(new_point)

For example, with

init_point = 0
def new_point_near_this_point(point):
    if point < 5:
        return point + 1

you get the list [0, 1, 2, 3, 4, 5].

Upvotes: 1

Related Questions