-1

I have a Python array.

arr = [1, 2, 3, 4, 5]

I want to remove N with a certain condition from the arr and store it again in the arr.

The condition: the remainder divided by 2 is 0 (it can be any other condition depending on the context)

For example, when removing N the remainder divided by 2 is 0, the result should be [1, 3, 5]. I want to use lambda for this but I don't know how.

Using JavaScript I can do this like this.

How can I achieve this?

David Buck
  • 3,752
  • 35
  • 31
  • 35
  • Possible solution: https://stackoverflow.com/questions/21510140/best-way-to-remove-elements-from-a-list – Ukiyo Nov 21 '20 at 14:06
  • 1
    Does this answer your question? [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value) – Equinox Nov 21 '20 at 14:07
  • if you show me waht it looks like in javascript maybe I can help you more because I am an avid python and javascript programer – TERMINATOR Nov 21 '20 at 14:23
  • Does this answer your question? [Best way to remove elements from a list](https://stackoverflow.com/questions/21510140/best-way-to-remove-elements-from-a-list) – nvidot Nov 21 '20 at 18:10

2 Answers2

1

If you lop through the array and remove any values with remainders you will get the desired affect:

This is how:

arr = [1,2,3,4,5]
#Loops through the array and removes values with a remaider

arr = [N for N in arr if N%2 != 0] 
print(arr)

Output: [1 , 3 ,5]

TERMINATOR
  • 1,180
  • 1
  • 11
  • 24
1

As you want a generic solution where you can change the formula, the normal Pythonic approach to this would be use a conditional logic in a list comprehension, for example:

arr = [1, 2, 3, 4, 5]
arr = [x for x in arr if x%2 != 0]

This recreates the list only with elements that match your criterion (so, as you want to remove elements where x%2 == 0, this flips in the list comprehension to only add items to the list where x%2 != 0.

As you did ask for a method that uses a lambda function, so you could (if you really wanted to, I can't say I recommend it) use:

func = lambda x : [x for x in arr if x%2 != 0]
arr = func(arr)

or

func2 =  lambda x : x%2 != 0
arr = [x for x in arr if func2(x)]
David Buck
  • 3,752
  • 35
  • 31
  • 35