My program, I want to delete some item from a list:
num_str = input('Enter a number: ')
num_num = int(num_str)
fac_list = list(range(1, num_num + 1))
print("BEFORE: ", fac_list)
for item in fac_list:
if num_num % item == 0:
fac_list.remove(item)
print("AFTER: ",fac_list)
output:
Enter a number: 8
BEFORE: [1, 2, 3, 4, 5, 6, 7, 8]
AFTER: [2, 3, 5, 6, 7]
It should be:
[3, 5, 6, 7]
What's wrong with it?
You are iterating over the list
and deleting it, that does not work how you want it to. This is because when you are iterating over the list, the for loop keeps track of the index you are currently at, but when you delete an item from the list, the index gets changed and hence you can end up skipping iterating over some elements.
You can just create a new list, with the values that you need (instead of deleting from old list) , and this can be done using list comprehension -
fac_list[:] = [x for x in fac_list if num_num % x != 0:]
The slice notation on left side is to make this inplace, so that fac_list
is changed inplace.
If you want to delete (and not create a new list) , you should iterate over its copy , Example -
for item in fac_list[:]:
if num_num % item == 0:
fac_list.remove(item)