Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing a number with each element of a list

Trying to write a program that compares a list of numbers to a previously defined variable, n. If the number is less than n, I want it to remove the number from the list. Whenever I try to print the numbers list after calling this function, it only removes the first number.

def larger_than_n():
    for item in numbers:
        if n > item:
            numbers.remove(item)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your function should take the list and the number as arguments, and return the modified list. Building a new list is easier than modifying the existing one in place; if you remove items from a list in a for loop over that same list, you end up "missing" items, which is the bug you’re running into.

def larger_than_n(numbers, n):
   """Return a new list of numbers larger than or equal to n."""
   return [item for item in numbers if item >= n]

print(larger_than_n([1, 2, 3, 2, 1], 2))
# [2, 3, 2]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading