tags:

views:

336

answers:

8

Consider this Python snippet:

for a in range(10):

    if a == 7:
        pass
    if a == 8:
        pass
    if a == 9:
        pass
    else:
        print "yes"

How can it be written shorter?

#Like this or...
if a ?????[7,8,9]:
    pass
+14  A: 

Use the in operator:

if a in (7,8,9):
    pass
z33m
a tuple is prefered as a list obejct
dzen
@dzen: Depends who you talk to. It's stylistic and being consistent is more important than what you choose, in this case.
Roger Pate
Tuples are usually preferred in such situations because they are faster and more efficient.
jcao219
+1  A: 
if a in [7,8,9]
Nick Fortescue
+14  A: 

To test if a falls within a range:

if 7 <= a <= 9:
  pass

To test if a is in a given sequence:

if a in [3, 5, 42]:
  pass
Roger Pate
The first variant is better, at least for this case!
Andrei Ciobanu
+2  A: 
for a in range(10):
    if a > 6:
        continue
    print('yes')
SilentGhost
A: 

Depending on what you want to do, the map() function can also be interesting:

def _print(x):
    print 'yes'

map(_print, [a for a in range(10) if a not in (7,8,9)])
Felix Kling
+1  A: 

What about using lambda.

>>> f = lambda x: x not in (7, 8, 9) and print('yes')
>>> f(3)
yes
>>> f(7)
False
Selinap
Use of the short circuit property of `and` seems to be discouraged. See one of Mike Graham's answers on stackoverflow for the reasons.
blokeley
+2  A: 

Since the question is tagged as beginner, I'm going to add some basic if-statement advice:

if a == 7:
    pass
if a == 8:
    pass
if a == 9:
   ...
else:
   ...

are three independent if statements and the first two have no effect, the else refers only to

 if a == 9:

so if a is 7 or 8, the program prints "yes". For future use of if-else statement like this, make sure to use elif:

if a == 7:
    seven()
elif a == 8:
    eight()
elif a == 9:
    nine()
else:
    print "yes"

or use just one if-statement if they call for the same action:

if a == 7 or a == 8 or a == 9:
    seven_eight_or_nine()
else:
    print "yes"
Joel
+2  A: 

Based on your original code the direct "pythonic" replacement is:

if not a in [7, 8, 9]:
     print 'yes'

or

if a not in [7, 8, 9]:
     print 'yes'

The latter reads a little better, so I guess it's a bit more "pythonic".

sdolan