Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way than using if-else statement in python [duplicate]

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

I am working on a python expression and I want that expression to be compressed than using the if else statement.

s = [1, 2, 3, 4]
if len(s)>5:
    print s.index(5)
else:
    print 'cant print'

Is there a better way than using as if else statement?

like image 571
sam Avatar asked Jul 15 '12 12:07

sam


People also ask

What can be used instead of if-else in Python?

Switch Case is a cleaner and faster alternative to if-else conditions in your code. Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.

What is faster than if-else in Python?

I found dict is faster than if-else. This means when I want to write a switch-statement, dict is better solution.

Is Elif faster than if?

Difference between if and if elif else Python will evaluate all three if statements to determine if they are true. Once a condition in the if elif else statement is true, Python stop evaluating the other conditions. Because of this, if elif else is faster than three if statements.


1 Answers

You can do:

s = [1, 2, 3, 4]
print 'y' if len(s) > 5 else 'n'

However I don't think this makes the code more readable (at a glance). Also note that if and else don't create a loop, they are simply statements for control flow. Loops are written using for and while.

like image 125
Simeon Visser Avatar answered Nov 15 '22 19:11

Simeon Visser