how to remove the first occurence of an integer in a list
<p>this is my code:</p>

<pre><code>positions = []
for i in lines[2]:
    if i not in positions:
        positions.append(i)
print (positions)
print (lines[1])
print (lines[2])
</code></pre>

<p>the output is: </p>

<pre><code>['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']
</code></pre>

<p>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.</p>

<p>You'll need to first detect what values are duplicated before you can build <code>positions</code>. Use an <code>itertools.Counter()</code> object to test if a value has been seen more than once:</p>

<pre><code>from itertools import Counter

counts = Counter(lines[2])
positions = []
for i in lines[2]:
    counts[i] -= 1
    if counts[i] == 0:
        # only add if this is the 'last' value
        positions.append(i)
</code></pre>

<p>This'll work for any number of repetitions of values; only the last value to appear is ever used.</p>

<p>You could also reverse the list, and track what you have already seen with a set, which is faster than testing against the list:</p>

<pre><code>positions = []
seen = set()
for i in reversed(lines[2]):
    if i not in seen:
        # only add if this is the first time we see the value
        positions.append(i)
        seen.add(i)
positions = positions[::-1]  # reverse the output list
</code></pre>

<p>Both approaches require two iterations; the first to create the <code>counts</code> mapping, the second to reverse the output list. Which is faster will depend on the size of <code>lines[2]</code> and the number of duplicates in it, and wether or not you are using Python 3 (where <code>Counter</code> performance was significantly improved).</p>

python python-3.x