Can just use plain list comprehension for this clean and easy to read.
Big-O doesn't matter here when dealing with a lists with few items,but if a make a bigger list will see a difference.
>>> names = ["Alice", "Bob", "Andrew", "Charlie"] >>> [name for name in names if name.startswith('A')] ['Alice', 'Andrew']Or the same with without.
names = ["Alice", "Bob", "Andrew", "Charlie"] new_list = [] for name in names: if name.startswith('A'): new_list.append(name) print(new_list)
Output:['Alice', 'Andrew']
For me is making in new list like over,is the preferred way/solution over copy [:]:
and reversed()
. names = ["Alice", "Bob", "Andrew", "Charlie"] for name in names[:]: if not name.startswith('A'): names.remove(name) print(names)
Output:['Alice', 'Andrew']
So it work fine,but remove()
has to go over the whole list for every iterationBig-O doesn't matter here when dealing with a lists with few items,but if a make a bigger list will see a difference.
import timeit # Modify original list remove = '''\ names = ["Alice", "Bob", "Andrew", "Charlie"] * 100 for name in names[:]: if not name.startswith('A'): names.remove(name)''' # Make new list list_comp = '''\ names = ["Alice", "Bob", "Andrew", "Charlie"] * 100 [name for name in names if name.startswith('A')]''' print(timeit.Timer(stmt=remove).timeit(number=1000000))So here use list comprehension 55-sec and remove use 6-minute.