Newbie_Android
Newbie_Android

Reputation: 235

Removing certain element in a list if element is multiples of a certain number

I would like to remove elements which are multiples of 5 from a list. In my code below "######" I tried >> number_list.pop(i) and it showed index out of range error. I also tried >> return number_list.pop(i) and it only seems to remove the first number which is 25. Codes in main() is given and I need to complete the function. I could easily do it by creating another list and store the numbers that are not multiples of 5 however it appears that I have to use the given list "numbers" to figure it out. I would be appreciated if I can get some help with this coding. Thank you.

ps. using python 3.5

def main():

    numbers = [25, 5, 9, 10, 15, 8]
    print(numbers)
    remove_multiples(numbers, 5) # remove multiples of 5
    print("Numbers left", numbers) 

def remove_multiples(number_list, multiples_of):


    for i in range(len(number_list)):
        if number_list[i] % multiples_of == 0:
            ################### 
    return number_list

main()

Upvotes: 0

Views: 172

Answers (3)

Hooting
Hooting

Reputation: 1711

def remove_multiples(number_list, multiples_of):
    pivot = 0
    for i,value in enumerate(number_list):
        if value % multiples_of != 0:
            number_list[pivot] = value
            pivot += 1
    del number_list[pivot:]
    return number_list

move the available element to front, and delete the rest

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81654

Removing an element from a list you're currently iterating over is never a good idea.

Instead, create and return a new list without the unnecessary elements using list comprehension:

def remove_multiples(number_list, multiples_of):
    return [num for num in number_list if num % multiples_of != 0]

print remove_multiples([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
>> [1, 3, 5, 7, 9]

Upvotes: 0

user5077528
user5077528

Reputation:

def main():  
    numbers = [25, 5, 9, 10, 15, 8]
    print(numbers)
    remove_multiples(numbers, 5) # remove multiples of 5
    print("Numbers left", numbers) 

def remove_multiples(number_list, multiples_of):
    for i in number_list:
        if i % multiples_of == 0:
            number_list.remove(i)
    return number_list

main()

Hope that's what you're looking for.

Upvotes: 0

Related Questions