Python Forum
.remove() method in for-loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
.remove() method in for-loop
#5
(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.16
Output:
time_1 --> 48.71 time_2 --> 2.16 time_3 --> 0.87 time_4 --> 87.82
Reply


Messages In This Thread
.remove() method in for-loop - by nzcan - Oct-08-2018, 07:39 PM
RE: .remove() method in for-loop - by ichabod801 - Oct-08-2018, 08:25 PM
RE: .remove() method in for-loop - by TimeMen - Oct-08-2018, 08:30 PM
RE: .remove() method in for-loop - by ichabod801 - Oct-08-2018, 08:34 PM
RE: .remove() method in for-loop - by snippsat - Oct-08-2018, 10:23 PM
RE: .remove() method in for-loop - by ichabod801 - Oct-09-2018, 01:04 AM
RE: .remove() method in for-loop - by snippsat - Oct-09-2018, 02:07 PM
RE: .remove() method in for-loop - by gruntfutuk - Oct-13-2018, 07:05 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020