Akul Chordia
Akul Chordia

Reputation: 11

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

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.

Upvotes: 1

Views: 1666

Answers (3)

uozcan12
uozcan12

Reputation: 427

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

Upvotes: 0

EnriqueBet
EnriqueBet

Reputation: 1473

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

Upvotes: 2

timgeb
timgeb

Reputation: 78700

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')

Upvotes: 1

Related Questions