Using if/else combination in a list comprehension in Python

Okay, you might know how to use conditionals in a list comprehension in Python, like so:

original_list=[1,2,3,4,5,6,7,8,9]
evens=[x for x in original_list if x%2==0]
odds=[x for x in original_list if x%2!=0]

This would create two lists, containing the even numbers and the odd numbers in original_list.

Now, using if/else is slightly different. Lets say you want to take a list of integers, and add 5 to all the even numbers, and add 4 to all the odd numbers. It's actually pretty easy:

original_list=[1,2,3,4,5,6,7,8,9]
result=[x+5 if x%2==0 else x+4 for x in original_list]
print result

this would be the output:
[5, 7, 7, 9, 9, 11, 11, 13, 13]

Another example is this (you figure out what it does):

print ''.join(['ha' if a else 'Mu' for a in range(4)] )+'!'

Written by Jannich Brendle Fri 26 October 2012 In Programming

tags: coollist comprehensionspython

Related posts

social