Search code examples
pythonmutability

How to modify the list elements with using no returning function


Really sorry for my bad English first,

I made two functions to continually modify (actually remove one by one) the elements in the list and to show the last element in the end, but the removing function is not giving impact on the list that I want to modify.

I think this is a problem about local-variables and mutability of list, but I don't know how to fix it.

At first, I give a list as an argument of one of the functions that I made, removing function. Removing function removes the element until it has only one element USING THE OTHER FUNCTION. In that function, I put my other function(I'll call this checking function) in. Checking function checks the elements to remove, and 'actually' remove one element in my code, but returns nothing.

Please note x and y variable is random value in range of length of seq (I did not write this in my example code), and they will be changed every time in while loop in removing function.

import random


def checking(x, y, seq):
    positions = [x, y]
    positions.sort()

    if seq[x] == 'b' and seq[y] == 'b':
        seq.pop(positions[1])
        seq.pop(positions[0])
        seq.append('a')
    else:
        seq.pop(positions[1])
        seq.pop(positions[0])
        seq.append('b')

def removing(seq):
    while len(seq) != 1:
        x, y = random1, random2
        remove(x, y, list(seq))
    return seq[0]

final(['a','a','b','a','b'])

I tested checking function is working well thus, I think this is problem of removing function.

I expected the list seq modified every time passing 'remove' function and finally return the last element, but there's nothing changed and stuck in infinite loop.

Thank you for reading my question.


Solution

  • list(seq) makes a new list instance where its items are shallow copies of seq items.

    The while loop never terminates for this reason as the list never empties.

    Pass the same seq to remove function instead of making a new list instance.

    remove(x, y, seq)
    

    When given argument is a tuple, convert it to a mutable list before going into the loop:

    seqm = list(seq)
    while len(seqm) != 1:
        x, y = random1, random2
        remove(x, y, seqm)
    return seqm[0]