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 very pythonic way is to use a list comprehension with a conditional expression:

>>> a = [2,4,5,12]
>>> a = [x-10 if x > 10 else x for x in a]
>>> a
[2, 4, 5, 2]

Need Your Help

Git - Pushing local branch to remote and making local branch track that remote branch

git version-control

I recently started using the GIT command line commands ( I used to use SourceTree).

Why does C# limit the set of types that can be declared as const?

c# constants compiler-errors

Compiler error CS0283 indicates that only the basic POD types (as well as strings, enums, and null references) can be declared as const. Does anyone have a theory on the rationale for this limitati...