1

I want to look in an array of elements. If an element exceeds a certain value x, replace it with another value y. It could be a bunch of elements that need to be replaced. Is there a function (code) to do this at once. I don't want to use for loop. Does the any() function help here? Thanks

1
  • By "array", do you mean list? Commented Dec 3, 2013 at 18:29

1 Answer 1

2

I really don't know how one could possibly achieve such a thing without the if statement.

Don't know about any() but I gave it a try with map since you don't want a for loop. But, do note that the complexity order (Big O) is still n.

>>> array = [1, 2, 3, 4, 2, -2, -3, 8, 3, 0]
>>> array = map(lambda x: x if x < 3 else 2, array)
>>> array
[1, 2, 2, 2, 2, -2, -3, 2, 2, 0]

Basically, x if x < 3 else 2 works like If an element exceeds a certain value x, replaces it with another value y.

Sign up to request clarification or add additional context in comments.

2 Comments

I think list comprehension is better than map lambda.
@Dani the OP did not want a use of for, hence no list comprehension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.