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?
-
1There seems to be a general consensus that an if/else statement is the best way to write it.Joel Cornett– Joel Cornett2012年07月15日 13:03:22 +00:00Commented Jul 15, 2012 at 13:03
-
I'm just guessing here, but it seems like the intentions of the OP is to avoid the if/elif/case/switch ugliness. Which ultimate solution would be a class-based solution, where the case-selection is done through polymorphism. This can lead to more concise code.Don Question– Don Question2012年07月15日 13:12:40 +00:00Commented Jul 15, 2012 at 13:12
-
After the latest edit, it seems like the OP only wants to do range checking...?thebjorn– thebjorn2012年07月15日 13:13:43 +00:00Commented Jul 15, 2012 at 13:13
-
yes actually if that index present, then only i want to find that element of that indexsam– sam2012年07月15日 13:17:26 +00:00Commented Jul 15, 2012 at 13:17
-
@don: sorry, i tried to ask by simpler way.sam– sam2012年07月15日 13:21:56 +00:00Commented Jul 15, 2012 at 13:21
5 Answers 5
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.
1 Comment
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'
8 Comments
isinstance sense -- bool is a subclass of int).In this case you could use the try/except block:
try:
print s.index(5)
except ValueError:
print "5 not in list"
2 Comments
s[5] (which would make it an IndexError). But I agree, this is the obviously Pythonic way of spelling range checking.Short and clear:
s = [1, 2, 3, 4]
output = {True: 'y',False: 'n'}
print output[len(s) > 5]
5 Comments
bool is-a int might be obscure, it is neither an implicit cast (it's a subtype) nor undocumented (see rationale throughout PEP 285: python.org/dev/peps/pep-0285 ). But yes, it definitely is obscure :-)Another variation:
print len(s)>5 and 'y' or 'n'
just added for completness. Don't try this at home! ;-)