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?

Answers


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

Android simple program run error

android

I have just installed Android SDK to my Eclipse, but when I run a simple program on Eclipse I get following error.

C++ to call python script to handle emailing

c++ python smtp

On a server I have a C++ program which takes some input and writes some output to a file. After the file is generated, I want to send an email to a person with the corresponding link to the file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.