Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more pythonic for array removal?

Tags:

python

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?

like image 251
bobobobo Avatar asked Nov 25 '25 23:11

bobobobo


2 Answers

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

like image 111
Soviut Avatar answered Nov 28 '25 14:11

Soviut


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.

like image 27
SilentGhost Avatar answered Nov 28 '25 12:11

SilentGhost