1
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.

3 Answers3

2

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

EnriqueBet
  • 1,482
  • 2
  • 15
  • 23
1

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')
timgeb
  • 76,762
  • 20
  • 123
  • 145
0
S=['TOM', 'HARRY', 'MAMA', 'JOE']
print(S)
for x in S[::-1]:
    print(S.pop())
    if S==[]:
        print("Empty")
        break
uozcan12
  • 404
  • 1
  • 5
  • 13