Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to condense if/else into one line in Python? [duplicate]

Tags:

python

Possible Duplicate:
Python Ternary Operator
Putting a simple if-then statement on one line

Is there a way to compress an if/else statement to one line in Python?
I oftentimes see all sorts of shortcuts and suspect it can apply here too.

like image 657
AnovaVariance Avatar asked Oct 05 '22 00:10

AnovaVariance


People also ask

How do you put multiple If statements in one line Python?

To put an if-then-else statement in one line, use Python's ternary operator x if c else y . This returns the result of expression x if the Boolean condition c evaluates to True . Otherwise, the ternary operator returns the alternative expression y .

How do you shorten if-else statements in Python?

Ternary Operator in Python A ternary operator exists in some programming languages, and it allows you to shorten a simple If-Else block. It takes in 3 or more operands: Value if true - A value that's returned if the condition evaluates to True .

Can we write if-else into one line in Python?

Python If Statement In One Line In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.


1 Answers

An example of Python's way of doing "ternary" expressions:

i = 5 if a > 7 else 0

translates into

if a > 7:
   i = 5
else:
   i = 0

This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.

The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.

It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.

like image 347
Levon Avatar answered Oct 17 '22 01:10

Levon