Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension - simple

I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified.

Example: Say I want to multiply by 2 only those elements who are even.

a_list = [1, 2, 3, 4, 5]

Wanted result:

a_list => [1, 4, 3, 8, 5]

But [elem * 2 for elem in a_list if elem %2 == 0] yields [4, 8] (it acted as a filter in addition).

What is the correct way to go about it?

like image 416
Lost_DM Avatar asked Oct 01 '11 11:10

Lost_DM


2 Answers

Use a conditional expression:

[x * 2 if x % 2 == 0 else x
 for x in a_list]

(Math geek's note: you can also solve this particular case with

[x * (2 - x % 2) for x in a_list]

but I'd prefer the first option anyway ;)

like image 197
Fred Foo Avatar answered Sep 22 '22 07:09

Fred Foo


a_list = [1, 2, 3, 4, 5]

print [elem*2 if elem%2==0 else elem  for elem in a_list ]  

or, if you have a very long list that you want to modify in place:

a_list = [1, 2, 3, 4, 5]

for i,elem in enumerate(a_list):
    if elem%2==0:
        a_list[i] = elem*2

so, only the even elements are modified

like image 30
eyquem Avatar answered Sep 24 '22 07:09

eyquem