Python Update Value in one Line?

Question:

In python I have:

c_f = None
#c_f may change here
if not c_f:
    c_f = new_c_f

Can I write last 2 lines in one line?

  1. If I want to keep first non-None value

  2. If I want to keep last non-None value

Please Note that doing:

c_f = c_f or new_c_f

solves one of the cases

Asked By: john

||

Answers:

Assuming you’re trying to squish

if not c_f:
    c_f = new_c_f

to one line, you can change it to a one-liner:

if not c_f: c_f = new_c_f
Answered By: Pto
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.