Skip to content

Instantly share code, notes, and snippets.

@domodomodomo
Last active January 27, 2018 16:46
Show Gist options
  • Save domodomodomo/cd4c36f5cc526d2f1d85bb8df2bbc8d2 to your computer and use it in GitHub Desktop.
Save domodomodomo/cd4c36f5cc526d2f1d85bb8df2bbc8d2 to your computer and use it in GitHub Desktop.
import timeit
def sample_code():
lst, v = [1, 5, 3, 4, 5, 6, 7, 5, 5, 10], 5
remove_equal(lst, v)
print(lst, v) # [1, 3, 4, 6, 7, 10] 5
def remove_equal_listcomprehension(lst: list, v):
new_lst = [e for e in lst if e != v]
lst.clear()
lst.extend(new_lst)
del new_lst
def remove_equal_for(lst, v):
for i, e in reversed(list(enumerate(lst))):
if e == v:
del lst[i]
def remove_equal_while(lst, v):
new_lst = []
pop = lst.pop
append = new_lst.append
while True:
try:
e = pop()
except IndexError:
break
if e == v:
del e
else:
append(e)
new_lst.reverse()
lst.extend(new_lst)
del new_lst
def remove_equal_filter(lst, v):
new_lst = list(filter(lambda x: x != v, lst))
lst.clear()
lst.extend(new_lst)
del new_lst
# remove_equal = remove_equal_listcomprehension
# remove_equal = remove_equal_for
# remove_equal = remove_equal_while
remove_equal = remove_equal_filter
if __name__ == '__main__':
sample_code()
print(timeit.timeit(
"remove_equal_listcomprehension([1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], 5)",
"from remove_equal import remove_equal_listcomprehension",
number=1000000))
print(timeit.timeit(
"remove_equal_for([1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], 5)",
"from remove_equal import remove_equal_for",
number=1000000))
print(timeit.timeit(
"remove_equal_while([1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], 5)",
"from remove_equal import remove_equal_while",
number=1000000))
print(timeit.timeit(
"remove_equal_filter([1, 2, 3, 4, 5, 6, 7, 8, 9 ,10], 5)",
"from remove_equal import remove_equal_filter",
number=1000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment