Home > Mobile >  Comparing a number with each element of a list
Comparing a number with each element of a list

Time:10-13

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)

CodePudding user response:

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]

CodePudding user response:

Try something like this, effectively we are:

  1. Creating a new empty list of numbers to eventually return
  2. Iterating over the original list of numbers checking if they are greater than n
  3. Adding them to our new list only if they are over n
  4. Returning the resulting new list

Here:

def larger_than_n(numbers, n):
    numbers_larger_than_n = []
    for number in numbers:
        if number > n:
            numbers_larger_than_n.append(number)
    return numbers_larger_than_n

numbers = [2, 3, 5, 7, 9, 11]
print(larger_than_n(numbers, 6))
[7, 9, 11]
  • Related