for loop and while loop

In python for loop has fixed number of iteration unless specified otherwise.

Below is a common for loop.

nums = range(5)

for i in nums:
    print(i)

It will print five numbers.

In while loop you can maniuplate number of iteration by changing index.

Consider the following for loop

i = 0
while i < 10:
    print(i)
    i += 2

It will print fiver even numbers less than 10.

For the same effect you can use for loop with slicing, but what if you want to remove value while you iterate over the same list?

As long as your index isn't our of range, you can achieve this with something like this

n = 5
nums = list(range(n))
while len(nums) > 1:
    nums.pop(n-1)
    n -= 1
print(nums)

It will print [0]. In this while loop the number of iteration is not set. Rather it changes dynamically according to the length of nums.

codingchallenge leetcode