Home > OS >  How do I pop a stack till it's empty using a FOR loop?
How do I pop a stack till it's empty using a FOR loop?

Time:06-02

S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S:
    print(S.pop())
    if S==[]:
        print("Empty")
        break

Using a for loop should iterate through the entire list and give me all the items followed by 'Empty' but instead, it only gives two elements

What I'm getting-

['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA

What I was expecting-

['TOM', 'HARRY', 'MAMA', 'JOE']
JOE
MAMA
HARRY
TOM
Empty

This is my first question here so any tips on how to frame questions would be appreciated.

CodePudding user response:

The main issue with your code is that you can't loop over a list while doing changes to that list. If you want to use a for loop (timgeb suggestion is great btw). You could do this:

for _ in range(len(S)):
    print(S.pop())

This will take care of popping all the items of the list

CodePudding user response:

You see an unexpected result because you're mutating the list while iterating over it. Note that you're not doing anything with x, so a for loop is not the right tool here.

Use a while loop.

while S:
    print(S.pop())

print('empty')

CodePudding user response:

S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S[::-1]:
    print(S.pop())
    if S==[]:
        print("Empty")
        break
  • Related