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?

asked Jul 15, 2012 at 12:35
5
  • 1
    There seems to be a general consensus that an if/else statement is the best way to write it. Commented 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. Commented Jul 15, 2012 at 13:12
  • After the latest edit, it seems like the OP only wants to do range checking...? Commented Jul 15, 2012 at 13:13
  • yes actually if that index present, then only i want to find that element of that index Commented Jul 15, 2012 at 13:17
  • @don: sorry, i tried to ask by simpler way. Commented Jul 15, 2012 at 13:21

5 Answers 5

17

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.

answered Jul 15, 2012 at 12:38
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed, this meets OPs request, but doesn't result in more readable code. +1 (reluctantly because of obfuscation)
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 Jul 15, 2012 at 12:42

8 Comments

How does that work? Does Python convert the boolean values to integers when indexing?
While technically correct, this is an awful answer IMO. For many people it will be hard to understand at first glance. Given that the answers to this question will most often be read by people new to the language and/or new to programming in general, I don't think suggesting such constructs is a good idea.
Python bools are ints (in the isinstance sense -- bool is a subclass of int).
@Bryan note that I explicitly said "don't do this", so I wouldn't call it a suggestion.
@thebjorn: while "(don't do this)" is better than nothing, your answer would be better if you spent just a little more effort explaining why someone shouldn't do that. Remember: the audience is mostly people who may not know why that's a bad idea. This is your chance to educate them.
|
7

In this case you could use the try/except block:

try:
 print s.index(5)
except ValueError:
 print "5 not in list"
answered Jul 15, 2012 at 13:21

2 Comments

may i ask why? thats a "pythonic" wy to use it! "Don't ask for permission, but for forgivness!" - Your if-clause is asking for permission and then does what it asked for. the try statment just does it and if it fails it handles the forgivness part.
Based on OP's comment on the question itself, it seems he actually meant s[5] (which would make it an IndexError). But I agree, this is the obviously Pythonic way of spelling range checking.
3

Short and clear:

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

5 Comments

Nothing against your solution, but I think the OP's original code is as "short and clear" is it gets when taking readability into account.
You are right, but I've decided to post it as "the right way" of avoiding if-else, instead of counting on some undocumented implicit casting that may get changed over time.
zenopy's solution is short, clear and is not without elegance ;-)
@zenpoy That is a good reason (and it's certainly clearer than the admittedly clever and cool, but obfuscating code that depends on the values of True/False)
@zenpoy while the fact that 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 :-)
0

Another variation:

print len(s)>5 and 'y' or 'n'

just added for completness. Don't try this at home! ;-)

answered Jul 15, 2012 at 13:00

3 Comments

I would give you points for archeological value, but otherwise this horribleness is why we got if-expressions into the language.
@thebjorn Wait, there was a version of python without if expressions?
@Marcin if-expressions were introduced in 2.5, before then we just had if-statements :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.