1

I am starting to learn python, and playing around with loops and lists. I can't understand how this doesn't continue till printing "The end"

x = [1,2,3,4]
for n in x:
    if len(x) > 0:
        x.pop(0)
        print(x)
    else:
        break
        print("The end")

I get:

[2, 3, 4]
[3, 4]
SuperStormer
  • 4,997
  • 5
  • 25
  • 35

1 Answers1

2

There's two bigger issues here.

  1. Don't modify an iterable as you loop over it. This makes the execution extremely difficult to rationalize about and can cause a lot of weird behavior.
  2. You put a break before the print. The break statement will exit the loop before you reach the print line.

Instead I would perform this action with a while loop, and do the end condition after the loop:

x = [1,2,3,4]
while len(x) > 0:
    x.pop(0)
    print(x)
print("The end")
[2, 3, 4]
[3, 4]
[4]
[]
The end
flakes
  • 21,558
  • 8
  • 41
  • 88