0

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.

Luigi
  • 45
  • 1
  • 8

2 Answers2

6

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I see! Thank you. My understanding of ternary conditional / assignment was off. It is var += (expression1 if condition else expression2) instead of my wrong understanding. Thanks again. – Luigi May 10 '14 at 07:23
0

Here is an easy one-liner that does the same transcription from DNA to RNA (T->U):

RNA = lambda x:''.join([{'A':'A','C':'C','G':'G','T':'U'}[B] for B in x])
print RNA("AGTCAGCAT") #example sequence results in AGUCAGCAU
Stefan Gruenwald
  • 2,582
  • 24
  • 30