Q:

# Remove items from a list while iterating using python programming

### Remove items from a list while iterating

Description:

In this question, You need to remove items from a list while iterating but without creating a different copy of a list.

Remove numbers greater than 50

Given:

``number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]``

Expected Output: -

`[10, 20, 30, 40, 50]`

Hint:

• Get the list's size
• Iterate list using while loop
• Check if the number is greater than 50
• If yes, delete the item using a `del` keyword
• Reduce the list size

Solution1:Using while loop

``````number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
i = 0
# get list's size
n = len(number_list)
# iterate list till i is smaller than n
while i < n:
# check if number is greater than 50
if number_list[i] > 50:
# delete current index from list
del number_list[i]
# reduce the list size
n = n - 1
else:
# move to next item
i = i + 1
print(number_list)``````

Solution2:Using for loop and range()

``````number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for i in range(len(number_list) - 1, -1, -1):
if number_list[i] > 50:
del number_list[i]
print(number_list)``````