Python program to delete from the list the numbers divisible by 5 returns wrong values

Viewed 1824

I wanted to delete from the list the numbers divisible by 5, but when the values divisible by 5 stand next to each other, it won't delete the second one. Can someone tell me what am I doing wrong? Here is the code:

my_list = []
n = int(input("Size of list: "))

for i in range(n):
    my_list.append(int(input("Enter value: ")))

for i in my_list:
    if i % 5 != 0:
        continue
    else: 
        my_list.remove(i)


print(my_list)
5 Answers

I'd build a new list with the good values:

new_list = [item for item in my_list if item % 5 != 0]

You are appending it in the same list. Like: if the array is 4,5,10,6 then firstly a[1] is 5 after you remove that from the list the for loop goes to a[2] which is now 6 as the new array is 4,10,6

Just loop through a copy of your list, so that removal of items will not affect the process. Amended lines are with comments:

my_list = []
n = int(input("Size of list: "))

for i in range(n):
    my_list.append(int(input("Enter value: ")))

my_list2=my_list.copy() #create a copy of my_list

for i in my_list2: #loop through my_list2
    if i % 5 != 0:
        continue
    else: 
        my_list.remove(i)


print(my_list)

When you delete an element at i = 5 the remaining elements shift to the left one position. So the next element at position 6 moves to the current position 5 and after increasing i by 1 you skip a number.

Use the filter function to create a new list with just the numbers that satisfy the condition.

my_list = []
n = int(input("Size of list: "))

for i in range(n):
    my_list.append(int(input("Enter value: ")))

filtered_list = list(filter(lambda x: x % 5 == 0, my_list))

print(filtered_list)

filtered_list = list(filter(lambda x: x % 5 != 0, my_list)) in above program. Instead of equal to write not equal to it works

my_list = [] n = int(input("Size of list: "))

for i in range(n): my_list.append(int(input("Enter value: ")))

filtered_list = list(filter(lambda x: x % 5 != 0, my_list))

print(filtered_list)

Related