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?