2

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

codeheadache
  • 134
  • 1
  • 15
  • 4
    ``duplicateList = listItems`` does not create a duplicate list. – MisterMiyagi Jul 13 '20 at 07:49
  • 5
    You should not remove items from a list while you are iterating over it. This is what you are doing because `listItems` is a reference to the same list as `duplicateList`. If you made a copy of the list and iterated over the copy, it would work. – alani Jul 13 '20 at 07:49
  • 2
    And you can make a copy using `duplicateList = listItems.copy()` (There is also something called `deepcopy` but it is not needed here.) – alani Jul 13 '20 at 07:51

0 Answers0