Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant pythonic way of expressing the following condional expression?

Tags:

python

I would like a more pythonic way for the following branch if any:

if a<b:
   a.append('value')
elif a==b:
   b.append('value')
else:
   do nothing

Is there any ternary operator for that?

like image 477
curious Avatar asked Feb 13 '13 10:02

curious


People also ask

How do I write more Pythonic code?

Another way to write more Pythonic functions is to have only one return statement. As your functions grow bigger, you may find yourself using multiple return statements within it. That said, having multiple returns will only make your functions difficult to read and modify.

What does it mean to be more pythonic?

Pythonic is an adjective that describes an approach to computer programming that agrees with the founding philosophy of the Python programming language. There are many ways to accomplish the same task in Python, but there is usually one preferred way to do it. This preferred way is called "pythonic."

What is Pythonic way?

From Python Syntax to Pythonic Style In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful. To help us better understand, let's briefly look at some aspects of the Python language.

Are IF statements Pythonic?

Python if statement is one of the most commonly used conditional statements in programming languages. It decides whether certain statements need to be executed or not. It checks for a given condition, if the condition is true, then the set of code present inside the ” if ” block will be executed otherwise not.


1 Answers

Use a nested ternary operator.

func1() if a<b else func2() if a==b else func3()

For your specific example:

a.append('value') if a<b else b.append('value') if a==b else None
like image 181
Volatility Avatar answered Oct 10 '22 03:10

Volatility