I am attempting to identify if an item is even and then removing them from any list and printing the new list
def remove_evens(my_list): if item in my_list 0 % 2 == 0: how do I remove the specified items? return list
CodePudding user response:
def remove_evens(my_list):
for item in my_list:
if item %2 == 0:
my_list.remove(item)
return my_list
my_list = [1,2,3,4,5,6]
remove_evens(my_list)
print(my_list)
CodePudding user response:
Try this:
numbers = [10, 20, 3, 15, 1000, 60, 16]
removed_evens = list(filter(lambda n: n % 2 != 0, numbers))
print(removed_evens)
And function form:
def removed_evens(numbers):
return list(filter(lambda n: n % 2 != 0, numbers))
Another logic:
def removed_evens(numbers):
results = []
for number in numbers:
if number % 2 != 0:
results.append(number)
return results
Which can be reduced to:
def removed_evens(numbers):
return [number for number in numbers if number % 2 != 0]
Or even more minimal:
removed_evens = lambda numbers: [number for number in numbers if number % 2 != 0]