Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
the PHP ternary operator equivalent on Python
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Steven D'Aprano, post: 1849355"] Why do you assume that everything you need for your list comprehension has to go into a single line? Chances are your list comp already calls functions, so just create one more for it to use. py> def describe(cond): .... if cond: .... return "odd" .... else: .... return "even" .... py> L = [describe(n % 2) for n in range(8)] py> L ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd'] One major advantage is that this makes it easier to test your function describe() in isolation, always a good thing. Another advantage is that the idiom "call a function" is extensible to more complex problems: def describe(n): if n < 0: return "negative " + describe(-n) elif n == 0: return "zero" elif n % 2: return "odd" else: return "even" L = [describe(n) for n in range(8)] if much easier to understand and follow than using ternary expressions: # obviously untested L = ["zero" if n == 0 else \ "negative " + ("odd" if n % 2 else "even") if n < 0 else \ "odd" if n % 2 else "even" for n in range(8)] Yes, I've seen ternary expressions nested three and even four deep. I find it fascinating to read Guido's reasoning for introducing a ternary statement. From the PEP here [URL]http://www.python.org/peps/pep-0308.html[/URL] he links to this comment of his: [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
the PHP ternary operator equivalent on Python
Top