0
Python: deleting a list item from additional appearances

I was attempting to create a program that can eliminate any additional occurrences of a list item, but it seems that there is something about loops that I don't understand.


list = [3, 2, 1, 4, 2, 3, 2]

list2 = list.copy()

list2.reverse()

l = len(list)

for i in range(l - 1):

for j in range(i+1, l):

if list[i] == list[j]: h = list[j]

list2.remove(h)

list2.reverse()

print(list2) the output: [3, 1, 4]

expected : [3, 2, 1, 4] (I got it after adding "break" under list2.remove(h))

Why is "break" necessary in this context, I wonder? Even without using "break," the block underneath if should only have been performed once. Alternatively, when I = 1 and j = 4 the if condition is satisfied and the block is run, "2" is removed once from list 2 and then again when I = 1 and j = 6. so why was another "2" dropped?


Python 19-03-23, 12:52 a.m. karlgamedev

Log-in to answer to this question.