lundi 13 juillet 2020

for loop behaving unexpectedly when used trying to remove passed list items [duplicate]

I am having a confusing time here. I have a list of items,which i pass it to a function. The function creates a duplicate list of the passed list, goes over each item, performs a string comparison and performs an action i.e remove. If i do not include the remove statement, the loop seems to be working alright but it behaves badly when i include it. Below is my code

def myFunction(listItems):
    list1 = ['a','b','c','d']    
    duplicateList = []
    duplicateList = listItems
    
    for temp in listItems:
        if temp == 'tab1':
                print("debug 1")
                duplicateList.remove('tab1')                                
                #duplicateList.remove('tab1')                
                           
        elif temp == 'tab3':
                print("debug 2")

        elif temp == 'tab2':
            print("debug 3")
            for tempList in list1:
                print("debug 4")

    return listItems
        
print(myFunction(['tab1', 'tab2', 'tab3']))

If duplicateList.remove('tab1') is commented out, the loop seems to work. However, even then the sequence of the loop is wrong. please guide me

Aucun commentaire:

Enregistrer un commentaire