Blog Entry 12 years, 10 months ago

New since Python 2.5: Conditional expressions

I tested some lines for replacing elements inside a list, somehow like this

I tested some lines for replacing elements inside a list, somehow like this:

>>> source_list = [1, 2, None, 4]
>>> new_list = [item if item else 'empty' for item in source_list]
>>> new_list
[1, 2, 'empty', 4]
>>>

It runs well while trying it with Python from console, and got failed when bringing into Plone. That's because the first Python is 2.7 and the latter is 2.4.x. I really like this lazy expression.

Actually, Conditional Expressions appeared since Python 2.5, here is the PEP: http://docs.python.org/release/2.5/whatsnew/pep-308.html

Recent Reads