Using if then else statement in list comprehension:
Traditional way of using list comprehension:
[item for item in list if (condition)]
Here we are using if statement only to filter out the elements.
Another way of using if statement:
[item_1 if (condition) else item_2 for item in list]
Here If then else statement is not directly implemented in list comprehension. Instead we are using it as a hack. We are actually placing conditional expression in place of the result.
Lets take an example with a problem,
Q) You have a list of characters and you have to switch the case of the characters in the list.
Input: I AM bhanu
Output: i am BHANU
This can be done using a single line using list comprehension,
input = raw_input()
input = [ch.lower() if ch == ch.upper() else ch.upper() for ch in input]
print ''.join(input)
No comments:
Post a Comment