Darrien Nguyen Darrien Nguyen - 5 days ago 6
Python Question

Removal of multiples of a number on a list:

I have a number two, I have this list, how would I go about removing multiples of the number 2 from that list and update it?

10 [2, 3, 4, 5, 6, 7, 8, 9, 10] 2

Answer

Methods:

Using a generator

One of the first option that comes to mind is to make use of a generator. The generator would iterate through a sequence, and test if the current element is divisible by n. This allows you to have a more generic solution as well:

def filter_by_multiple(seq, n):
    for i in seq:
        if i % n:
            yield i

Usage:

>>> filter_by_multiple([2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
<generator object filter_by_multiple at 0x000000374ED30258>
>>> list(filter_by_multiple([2, 3, 4, 5, 6, 7, 8, 9, 10], 2))
[3, 5, 7, 9]
>>> 

Using a generator expression

While the above solution is fine, is can be shorten even more by using generator expressions. generator expression are list list comprehensions, but unlike them, they return a generator iterator.

Usage:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(el for el in l if el % 2)
[3, 5, 7, 9]
>>> 

Using filter():

Among many of the builtin functions in Python, there is one for filtering list called filter(). The usually way to use filter() is to pass in the function you want to use to filter your list, and then the actual list you want filtered. In your case, you want to filter out every element the is not a multiple of two:

Usage:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(filter(lambda x: x % 2, l))
[3, 5, 7, 9]
>>> 

Using a list comprehension

While all of the above are fine ways for filtering a list, probably the most obvious and canonical, is to use a list comprehension. In your case, your list comprehension, is dead simple.

Usage:

>>> l = [2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [el for el in l if el % 2]
[3, 5, 7, 9]
>>>
Comments