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 :
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]