0
Python - What does happen in this code? Why is output 18?
arr = [0,1,2,3,4,5] sum = 0 for n in arr: sum = sum + n if(n==3): arr.insert(n,10) print (arr) if(sum>15): break print (sum)
1 Answer
+ 5
n is added to the sum first.
When n == 3, 10 is inserted to index 3. Then the iteration continues. The next element is still 3 because 10 is inserted. 3 is added again and 10 is inserted again because n == 3. And again, again, again....Until sum > 15 it breaks
0+1+2+3+3+3+3+3 = 18 (Done 5 times)