Rabin Rabin - 3 months ago 6
Python Question

how to remove the first occurence of an integer in a list

this is my code:

positions = []
for i in lines[2]:
if i not in positions:
positions.append(i)
print (positions)
print (lines[1])
print (lines[2])


the output is:

['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']


I would want my output of the variable "positions" to be; ['2','3','4','1','5']
so instead of removing the second duplicate from the variable "lines[2]" it should remove the first duplicate.

Answer

You can reverse your list, create the positions and then reverse it back as mentioned by @tobias_k in the comment:

lst = ['1', '2', '3', '4', '1', '5']

positions = []
for i in reversed(lst):
    if i not in positions:
        positions.append(i)

list(reversed(positions))
# ['2', '3', '4', '1', '5']
Comments