Skip to content

Instantly share code, notes, and snippets.

@markgreene74
Created February 19, 2023 15:10
Show Gist options
  • Select an option

  • Save markgreene74/3773be2773ecd61f3e59370008541336 to your computer and use it in GitHub Desktop.

Select an option

Save markgreene74/3773be2773ecd61f3e59370008541336 to your computer and use it in GitHub Desktop.
random-notes-2023-02-19
>>> l = list(range(10))
>>> def f(l,d=False):
...  for i in l:
...   if d:
...    l.remove(i)
...   else:
...    yield i
... 
>>> list(f(l))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(f(l,d=True))
[]
>>> l
[1, 3, 5, 7, 9]
>>>

This example is not good Python, one should never modify a list while iterating it. There is a number of good SO posts about this, an example can be found here.

example 1

Make a deepcopy of the list:

from copy import deepcopy


def f(_list, remove_condition=False):
    _ = deepcopy(_list)
    for i in _:
        if remove_condition:
            _.remove(i)
        else:
            yield i

example 2

Or change the remove flag around and do this:

def f(_list, do_not_remove_condition=True):
    for i in _list:
        if do_not_remove_condition:
            yield i
        else:
            yield

example 2b

We can make that even shorter:

def f(_list, do_not_remove_condition=True):
    for i in _list:
        yield i if do_not_remove_condition else None

Also note that in this case we will get a None value for each element that is removed.

example 3

And finally, unless we really need a generator, why not a simple list comprehension:

new_l = [i for i in l if not remove_condition]

I used a bool in the examples for simplicity, but remove_condition could be a function that validates each element of the list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment