0

Why does the break statement return a differrent result?:

Input 1:

list1 = [1,2,3,4]
for i in range(len(list1)):
    for i in list1:
        list1.remove(i)
        print(i, list1)
        #break

Output 1:

(1, [2, 3, 4])
(3, [2, 4])
(2, [4])
(4, [])

Input 2:

for i in range(len(list1)):
    for i in list1:
       list1.remove(i)
       print(i, list1)
       break

Output 2:

(1, [2, 3, 4])
(2, [3, 4])
(3, [4])
(4, [])
Arda Arslan
  • 1,331
  • 13
  • 24
Panic
  • 325
  • 2
  • 10
  • ... Because the second snippet only touches the first element. – Ignacio Vazquez-Abrams Jul 11 '18 at 02:36
  • 3
    Changing a list while iterating over it is a bad idea in Python. (You can imagine it as a `while index <= len(list1): … index += 1`.) – Ry- Jul 11 '18 at 02:37
  • Also, you're using the variable `i` for both the outer loop and the inner loop. The outer loop is essentially useless. – blhsing Jul 11 '18 at 02:41
  • @blhsing The outer loop is still looping and hence repeating the inner loop, so it is not useless. The variable used -- yes, that's useless. – zondo Jul 11 '18 at 02:44

0 Answers0