0

I used a for loop to remove the duplicates in a list from the left side. For example, [3,4,4,3,6,3] should be [4,6,3]. And also the sequence cannot be changed, that's why I cannot use a set here. If I use set() here, the result would be [3,4,6].

def solve(arr): 
    for i in arr:
        if i in arr[arr.index(i)+1:]:
            arr.remove(i)
    return arr

solve([1,2,1,2,1,2,3])

It should return [1,2,3]. Instead, I got [2,1,2,3]. I viewed the visualized execution of the code, and it seems when python got to the item '2' the second time, meaning when the arr is mutated to be [2,1,2,3], it just suddenly stopped iteration from the for loop and returned the list as it is. When it should detect there is still another '2' in the list. Please help

Sophie
  • 25
  • 4
  • 6
    Rule #1: Don't remove item from list while iterating over it, it's like cutting off tree branch on which you sit. – Austin Feb 02 '19 at 10:56
  • 2
    ... You could use `set()` if order of elements in result does not matter. – Austin Feb 02 '19 at 11:00
  • ...and if you don't want to use `set` (which is really the simplest solution here) then iterate over your list but don't remove anything from it. Instead, create a new list and add items to to it. – Karl Feb 02 '19 at 11:09
  • Sorry I forgot to say that the sequence does matter, which is why I couldn't use set() here. And I agree that changing a list while iterating over it is not good practice, but I just want to understand why the last iteration is not being executed. – Sophie Feb 02 '19 at 11:57

2 Answers2

0

You can use set for this:

a  = [1,2,1,2,1,2,3]
b = set(a)

Then b will be:

{1,2,3}
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You can try this way:

def solve(arr):
    another_arr = []
    for i in arr:
        if i in another_arr:
            another_arr.remove(i)
            another_arr.append(i)
        else:
            another_arr.append(i)
    return another_arr


print(solve([1, 2, 1, 2, 1, 2, 3]))
Partho63
  • 3,117
  • 2
  • 21
  • 39