(Oct-08-2018, 08:30 PM)TimeMen Wrote: Why not doing like this?If think about it's about 8-9 function call for that short list,without running profile on it.
ichabod80 Wrote:Or you could do a list comprehension:It's about as pythonic as it get.
It work well in most cases small or big list.
I think
set()
can be fast if have larger list.>>> sw = ['go', 'bo', 'bo', 'bo', 'bo'] >>> set(sw) - set(['bo']) {'go'}Can do some measuring with timeit.
import timeit def time_1(lst): for i in range(0, lst.count("bo")): lst.remove("bo") def time_2(lst): sw = [item for item in lst if item != 'bo'] def time_3(lst): set(lst) - set(['bo']) def time_4(lst): while 'bo' in lst: lst.remove('bo') lst = ['time_1', 'time_2', 'time_3', 'time_4'] for test in lst: t = timeit.Timer(f"{test}(['go', 'bo', 'bo', 'bo', 'bo'])", f'from __main__ import {test}').timeit(number=10000000) print(f'{test} --> {t:.2f}')
Output:time_1 --> 13.59
time_2 --> 7.83
time_3 --> 9.11
time_4 --> 10.88
Now make list bigger *100
,and run it a little less average iteration number=100000
.Now see that
set()
shine 0.87,and list comprehension still okay with 2.16Output:time_1 --> 48.71
time_2 --> 2.16
time_3 --> 0.87
time_4 --> 87.82