Reputation: 20000
I have a list in python and I want to make sure that all values in the list are greater than some value. If not then I want to set it to that value.
eg: let us assume the list is
a = [1,2,3,4]
and the value to compare is 3. So I want the list to become
a = [3,3,3,4]
I can do this by iterating through all the elements in the list. Is there a better way to do that?
Upvotes: 2
Views: 3325
Reputation: 239513
You can reconstruct the list with a simple conditional expression and list comprehension, like this
a = [1, 2, 3, 4]
print [item if item > 3 else 3 for item in a]
# [3, 3, 3, 4]
For every item
in a
, it checks if it is greater than 3
, then use item
as it is otherwise use 3
.
This is similar but very efficient than the following,
result = []
for item in a:
if item > 3:
result.append(item)
else:
result.append(3)
But remember that list comprehension creates a new list. So, you have may have to do
a = [item if item > 3 else 3 for item in a]
Upvotes: 4