Geni-sama
Geni-sama

Reputation: 317

How to end a While-Loop when value is met inside a Nested List in Python?

I have a nested List and I am trying to end a while-loop when a value inside the nested loop is searched through For-Loop. My problem is it is looping forever.

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
point = ''
while point is not endpoint:
    for sets in listA:
        for point in sets:
            print(point)

I want the output to be like this:

a
b
b
c

Upvotes: 2

Views: 567

Answers (2)

Julio Suriano
Julio Suriano

Reputation: 151

Yash's answer does the job.

Another way you can do it is by defining a function and returning when point is equal to endpoint.

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'

def foo(items, endpoint):
    for sets in items:
        for point in sets:
            print(point)
            if point == endpoint:
                return

foo(listA, endpoint)

But to answer your question why it doesn't work, it is because the second for loop will always execute completely and the value of point will always be the last value of the last set in the list (in this case 'e'). So that is why the while loop will run forever as it will always check if 'e' is not 'c' evaluating to true.

If you want to keep your old solution you can do this:

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
point = ''
while point != endpoint:
    for sets in listA:
        for point in sets:
            print(point)
            if endpoint == point:
                break
        else: 
            continue
        break

It is basically braking from the nested for loops when point is equal to endpoint.

As you can see you check if point and endpoint are the same twice (in the if endpoint == point and in the while loop), so the while loop is unnecessary.

Upvotes: 1

Yash Goyal
Yash Goyal

Reputation: 174

you can do:-

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
done = False
for sets in listA:
    if done:
        break
    for point in sets:
        print(point)
        if point == endpoint:
            done=True
            break

Upvotes: 4

Related Questions