Search code examples
pythonaugmented-assignment

Python ternary conditional for joining string


Answered by Martijn Pieters. Thank you.
It is because statement vs expression. And because .join() does not mutate (is a pure function), so it needs to be assigned to a variable.

Question:
What is the reason for this oddity?

Goal:

if base == 'T':
    RNA_seq += 'U'
else:
    RNA_seq += base

This following method works:

# += in expression1 and .join() in expression2
RNA_seq += 'U' if base == 'T' else RNA_seq.join(base)
# Edit note: RNA_seq.join(base) works because it returns `base`
#       aka. RNA_seq += 'U' if base == 'T' else base

However the following does NOT work:

# Using += on both expressions
RNA_seq += 'U' if base == 'T' else RNA_seq += base

or

# Using .join() for both expressions
RNA_seq.join('U') if base == 'T' else RNA_seq.join(base)

The results are the same in both Python2 and Python3.


Solution

  • Like all assignment, += is a statement. You cannot ever put statements in an expression. The right-hand expression (everything after +=) is evaluated first, the result of which is then used for the augmented assignment.

    You can do:

    RNA_seq += 'U' if base == 'T' else base
    

    Now the expression resolves either to 'U', or base, depending on the value of base.

    If 'U' if base == 'T' else RNA_seq.join(base) worked, then that means that RNA_seq.join() returns a new value and doesn't mutate RNA_seq in-place. RNA_seq.join('U') if base == 'T' else RNA_seq.join(base) would then also return a new value, leaving the original value bound by RNA_seq unchanged, and you didn't assign it back to RNA_seq.