Replacing an element from list after checking for condition in python: doing it the "pythonic way"
I have a list of numbers such as:
a = [2,4,5,12]
I want to change the list by subtracting 10 from any element that is greater than 10.
I can do the following for that:
i = 0 for ax in a: if ax>10: ax = ax-10 a[i] = ax i = i+1
But this is not a "pythonic" way of coding. I would be fine with this loop if I was using Fortran but Python is better than these structured loops.
Can I do this in another way?
>>> a = [2,4,5,12] >>> a = [x-10 if x > 10 else x for x in a] >>> a [2, 4, 5, 2] >>>