Skip to content Skip to sidebar Skip to footer

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 mult

Solution 1:

Use a conditional expression:

[x * 2if x % 2 == 0else x
 forxin 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 ;)

Solution 2:

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

print [elem*2if elem%2==0else 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 inenumerate(a_list):
    if elem%2==0:
        a_list[i] = elem*2

so, only the even elements are modified

Solution 3:

You could use lambda:

>>>a_list = [1, 2, 3, 4, 5]>>>f = lambda x: x%2and x or x*2>>>a_list = [f(i) for i in a_list]>>>a_list
[1, 4, 3, 8, 5]

Edit - Thinking about agf's remark I made a 2nd version of my code:

>>>a_list = [1, 2, 3, 4, 5]>>>f = lambda x: x if x%2else x*2>>>a_list = [f(i) for i in a_list]>>>a_list
[1, 4, 3, 8, 5]

Post a Comment for "Python List Comprehension - Simple"