modify lists removing elements without making a mess
<p>I'm trying to resolve now a task that sounds like that:</p>

<blockquote>
  <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p>
</blockquote>

<p>For example:</p>

<ul>
<li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li>
<li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li>
</ul>

<p>So the functin should return:
['bear','elephant']
['cat','dog','duck']</p>

<p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p>

<pre><code>def confront(s1, s2):   

    if s1 &lt; s2:   # condition that tells which element to choose later
        return 0
    elif s2 &lt; s1:
        return 1
    else:
        return 2


def modi(la,lb):

    latemp = []

    lbtemp = []

    i = 0

    while i &lt; len(la):


        q = confront(la[i], lb[i])
        if q == 0:
            latemp.append(la[i])

        elif q == 1:
            lbtemp.append(lb[i])


        i +=1  
    la = latemp
    lb = lbtemp
    return la, lb
</code></pre>

<p>I have tried remove() but it have created a big mess</p>

<p>Generally, when you're mutating a list while iterating over it. It's good practice to iterate over a copy instead. Below is an example of what you would do to mutate one list.</p>

<pre><code>list = []
list_copy = list[:]
for i in list_copy:
    list.remove(i)
return list
</code></pre>

<p>This allows you to maintain the correct index per iteration.</p>

<p>Below is my attempt to explain what I meant and using a for loop to get your expected result. Hope it helps.</p>

<pre><code>def confront(s1, s2):

if s1 &lt; s2:   # condition that tells which element to choose later
    return 0
elif s2 &lt; s1:
    return 1
else:
    return 2


def modi(la,lb):
    la_copy = la[:]
    lb_copy = lb[:]

    for i in range(len(la_copy)):
        q = confront(la_copy[i], lb_copy[i])
        if q == 0:
            lb.remove(lb_copy[i])
        elif q == 1:
            la.remove(la_copy[i])

    return la, lb


la = ['bear', 'tiger', 'wolf', 'whale', 'elephant']
lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']
</code></pre>

<p>Calling it via a print() will get the returned two lists.</p>

<p>Note: this returns a tuple. IF you'd like seperate lists call it via the following.</p>

<pre><code>list1, list2 = modi(la,lb)
print(list1)
print(list2)
['bear', 'elephant']
['cat', 'dog', 'duck']
</code></pre>

python list python-3.x