What's more pythonic for deleting an array?

I am removing the item from the array if it exists.

Two ways I can think of this

Path number 1

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

Path number 2

try:
  x.remove (r)
except:
  pass

The timelines show that the try / except <method could be faster

(several times I get :)

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

What's more pythonic?

+2


source to share


5 answers


I always went with the first method. if in

reads much more clearly than exception handling.



+6


source


which will:

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

      



btw, you had to try to remove an item that is not in the list in order to have a comprehensive comparison.

+5


source


The speed depends on the ratio of hits and misses. To be pythonic, choose a clearer method.

Personally, I think path # 1 is clearer (it takes fewer lines to have an "if" block, not an exception block, and also less brain space). It will also be faster when there are more hits than misses (an exception is more expensive than missing an if block).

+3


source


Try / except method

+2


source


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

There is nothing about this in PEP-8 , so depending on which you prefer, this is the "real" answer.

Speaking of PEP-8 ... having this space before the colon falls under the definition of "extraneous spaces".

+1


source







All Articles