views:

172

answers:

5

I'm removing an item from an array if it exists.

Two ways I can think of to do this

Way #1

# x array, r item to remove
if r in x :
  x.remove( r )

Way #2

try :
  x.remove( r )
except :
  pass

Timing it shows the try/except way can be faster

(some times i'm getting:)

1.16225508968e-06
8.80804972547e-07

1.14314196588e-06
8.73752536492e-07
import timeit

runs = 10000
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
  'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
  'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
  'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'

code1 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
  'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
  'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
  'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'

if r in x :
  x.remove(r)
"""
print timeit.Timer( code1 ).timeit( runs ) / runs

code2 ="""
x = [ '101', '102', '103', '104', '105', 'a', 'b', 'c',
  'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', '111', '112', '113',
  'x', 'y', 'z', 'w', 'wwwwwww', 'aeiojwaef', 'iweojfoigj', 'oiowow',
  'oiweoiwioeiowe', 'oiwjaoigjoaigjaowig',
]
r = 'a'

try :
  x.remove( r )
except :
  pass
"""
print timeit.Timer( code2 ).timeit( runs ) / runs

Which is more pythonic?

+2  A: 

The try/except way

truppo
Could have problems, if some other error occurs.
Peter
+5  A: 

that would be:

try:
  x.remove(r)
except ValueError:
  pass

btw, you should have tried to remove an item that is not in the list, to have a comprehensive comparison.

SilentGhost
Why do you think this is clearer (the most import ingredient in being pythonic).
Peter
Because it's easier to ask forgiveness than to get permission. Your definition is too rather subjective
SilentGhost
+1  A: 

The first way looks cleaner. The second looks like a lot of extra effort just to remove an item from a list.

There's nothing about it in PEP-8, though, so whichever you prefer is the 'real' answer.

Speaking of PEP-8... having that space before the colon falls under the definition of 'extraneous whitespace'.

nilamo
+5  A: 

I've always gone with the first method. if in reads far more clearly than exception handling does.

Soviut
To all who are downvoting, please understand that the OP asked for the 'most pythonic' way, not the 'most efficient'.
Soviut
+3  A: 

Speed depends on the ratio of hits to misses. To be pythonic choose the clearer method.

Personally I think way#1 is clearer (It takes less lines to have an 'if' block rather than an exception block and also uses less brain space). It will also be faster when there are more hits than misses (an exception is more expensive than skipping a if block).

Peter