Search code examples
pythonloopsenumerate

Trying remove function with enumerate in loops


I am currently learning python, and I recently knowing there is function called enumerate, so I try to get myself better understanding by figuring out another way to solve this problem from Coursera. Whats happen is I am trying to use remove function to modify the list after duplicating the original list, so the for loops does not confused (it iterates the original, but I modify the duplicate list). Can anyone maybe knowing whats wrong with my code? Thanks before for the help.

def skip_elements(elements):
    # code goes here
    #new_elements=[]
    dup = elements
    for count, val in enumerate(elements):
        #if count % 2 == 0:
        #   new_elements.append(val)
        if count % 2 == 1:
            dup.remove(val)
    #return new_elements
    return dup

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) 
# Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) 
# Should be ['Orange', 'Strawberry', 'Peach']

Solution

  • You have not duplicated the list. You just created a new reference to the same list. Use elements[:] to create a shallow copy. -@KlausD

    dup = elements.copy(). Read more about what @KlausD. mentioned about it being reference Facts and myths about Python names and values – Ch3steR

    After a slight reading from mr Ch3steR's reference, basically this part of the code dup = elements did not copy or duplicate the original list, but only referencing the same list, thats why if I edit (remove) that same list, it will go chaos. The solution is using elements[:] or dup = elements.copy().

    Great Thanks to @KlausD and @Ch3steR from the comment.