Need help finding bug in the code

Need help finding bug in the code
0

#1

I use below code to remove numbers smaller than 5 from the list nums. However, it does not work as expected. Can anyone help me with finding out the bug?
>>> nums=[1,2,5,10,3,100,9,24]
>>> for i in nums:
if i<5:
nums.remove(i)
>>> nums
[2, 5, 10, 100, 9, 24]

#2

Could the following work?

``````nums.remove(nums[i])
``````

And I also believe it should be

``````if nums[i] < 5:
``````

#3

Just adding my take on the problem:

``````nums = [1, 2, 5, 10, 3, 100, 9, 24]
nums = [i for i in nums if i >= 5]
# [5, 10, 100, 9, 24]
# Use i > 5 If 5 is not to be included
``````

#4

This code checks for each element in nums- is it smaller than 5? If it is, it removes that element. In the first iteration, 1 indeed is smaller than 5. So it removes that from this list. But this disturbs the indices. Hence, it checks the element 5, but not the element 2. For this situation, we have three workarounds:

1. Create an empty array in python and append to that-
``````>>> nums=[1,2,5,10,3,100,9,24]
>>> newnums=[]
>>> for i in nums:
if i>=5:
newnums.append(i)
>>> newnums
``````

[5, 10, 100, 9, 24]

1. Using a list comprehension-
``````>>> nums=[1,2,5,10,3,100,9,24]
>>> newnums=[i for i in nums if i>=5]
>>> newnums
``````

[5, 10, 100, 9, 24]

1. Using the filter() function-
``````>>> nums=[1,2,5,10,3,100,9,24]
>>> newnums=list(filter(lambda x:x>=5, nums))
>>> newnums
``````

[5, 10, 100, 9, 24]