Python List Comprehensions 1 - Swap Case

Hacker Rank Swap Case One-Liner Solution with List Comprehension

Python list comprehensions are an awesome way to condense common loops into one line of code. When we need to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition, it makes sense to use a list comprehension.

The sWAP cASE Hacker Rank problem is simple but good practice for a list comprehension.

Task: You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

The solution uses an intermediary list to hold all the characters from the original string. It loops over the characters and checks if they are alphabetical characters, if so, it swaps case using Python's built-in string method swapcase(). If the character is not alphabetical, leave it alone and add it to the list. Finally, join the list with no delimiters.

def swap_case(s):

    final = []
    for char in s:
        if char.isalpha():
           final.append(char.swapcase())
        else: final.append(char)
    return ''.join(final)

Simple enough. With a list comprehension combined with a conditional expression, I was able to condense six lines of code into this one line:

def swap_case(s):

    return ''.join([char.swapcase() if char.isalpha() else char for char in s ])

Awesome! Now how to remember how list comprehension syntax?

For loop with if/else: [f(x) if condition else g(x) for x in sequence]

for loop with if: [f(x) for x in sequence if condition]

Do you think the one-liner is better than the 6 lines of code?