I want to remove duplicates from a list. I know it can be done easily with list(dict.fromkeys(my list))
, but I want to do it by iterating through the list. When I am removing a duplicate number from the list, the loop variable j
causes an Index error : list index out of range
later in subsequent iterations, even though I am changing the range input. I am wondering how to change loop variable inside loop ?
def rem_duplicate(seq):
for i in range(len(seq)):
num = seq[i]
count = 0
length = len(seq)
for j in range(length):
if seq[j] == num:
count += 1
if count > 1:
del seq[j]
length=length-1
return seq
my_list = [2, 3, 4, 5, 6, 7, 8, 3, 4, 1, 5, 2, 5, 7, 9]
print(rem_duplicate(my_list))