Alex Rivera | Logout

better way than using if-else statement in python

Asked 2012-07-15T12:35:45.110
13

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?

Edit
Report

2 Answers

13

Short, but very obfuscated (don't do this):

print 'ny'[len(s) > 5]

[edit] the reason you should never do this, is because it uses properties of the language that are little known to most people, i.e. that bool is a subclass of int. In most situations where you find yourself writing code like the OP, it's usually better to create a flag variable

s_is_long = len(s) > 5

then you can use any of the more appropriate ways to write the print, e.g.:

print 'y' if s_is_long else 'n'

or

print {True: 'y', False: 'n'}[s_is_long]

or the most readable of all...

if s_is_long:
    print 'y'
else:
    print 'n'
answered 2012-07-15T12:42:18.457
3

Short and clear:

s = [1, 2, 3, 4]
output = {True: 'y',False: 'n'}
print output[len(s) > 5]
answered 2012-07-15T12:53:35.143

Your Answer