Max Between a List and an Int

I have a list which I need all elements to be compared with an int and then return a list.

For example:

mylist = [1, 5, -2, 7]

something like this:

max(mylist, 0) => [1, 5, 0, 7]

How should I do that?

2

3 Answers

Something like this?

num = 0
mylist = [1, 5, -2, 7]
ans = [e if e>=num else num for e in mylist]
print(ans)

Output:

[1, 5, 0, 7]
5

Create a new list by

  • iterating over the orignal
    • make the comparison with the int
    • keep the value that meets the criteria

NumPy library with the power of SIMD instructions provides that. Generally, if you have a list or array called a:

import numpy as np    
a = np.array([1, -2, 3, 4, 5, -6, -7, -8, 9])

note using a NumPy array instead of a list makes the computation much faster, faster than any for loop. Vice versa using NumPy for lists is not efficient as a for loop.

np.maximum(0, a)

Output:

[1 0 3 4 5 0 0 0 9]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest