Python find and replace last appearance in list
<p>In Python, I have a list of list</p>

<pre><code>list3 = ['PA0', 'PA1']
list2 = ['PB0', 'PB1']
list1 = ['PC0', 'PC1', 'PC2']

[(list1[i], list2[j], list3[k]) for i in xrange(len(list1)) for j in xrange(len(list2)) for k in xrange(len(list3))]

#Result
[('PC0', 'PB0', 'PA0'), 
('PC0', 'PB0', 'PA1'), 
('PC0', 'PB1', 'PA0'), 
('PC0', 'PB1', 'PA1'), 
('PC1', 'PB0', 'PA0'), 
('PC1', 'PB0', 'PA1'), 
('PC1', 'PB1', 'PA0'), 
('PC1', 'PB1', 'PA1'), 
('PC2', 'PB0', 'PA0'), 
('PC2', 'PB0', 'PA1'), 
('PC2', 'PB1', 'PA0'), 
('PC2', 'PB1', 'PA1')]
</code></pre>

<p>How can I find the <strong>last appearance</strong> and add <strong>E</strong> as suffix</p>

<pre>
[('PC0', 'PB0', 'PA0'), 
 ('PC0', 'PB0', 'PA1'), 
 ('PC0', 'PB1', 'PA0'), 
 (<b>'PC0E'</b>, 'PB1', 'PA1'), 
 ('PC1', 'PB0', 'PA0'), 
 ('PC1', 'PB0', 'PA1'), 
 ('PC1', 'PB1', 'PA0'), 
 (<b>'PC1E'</b>, 'PB1', 'PA1'), 
 ('PC2', 'PB0', 'PA0'), 
 ('PC2', <b>'PB0E'</b>, 'PA1'), 
 ('PC2', 'PB1', <b>'PA0E'</b>), 
 (<b>'PC2E'</b>, <b>'PB1E'</b>, <b>'PA1E'</b>)]
</pre>

<p>Another approach that gathers keeps adding the indexes so you end up with the indexes for the last occurrence, <em>itertools.product</em> will also create the initial list for you:</p>

<pre><code>from itertools import product

def last_inds(prod):
    # the key/value will be overwritten so we always keep the last seen
    return {ele: (i1, i2) for i1, prod in enumerate(prod) for i2, ele in enumerate(prod)}

prod = list(product(*(list1, list2, list3)))

# use the indexes to change the last occurrences.
for r, c in last_inds(prod).values():
    lst = list(prod[r])
    lst[c] += "E"
    prod[r] = tuple(lst)
</code></pre>

<p>Which gives you the expected output:</p>

<pre><code>[('PC0', 'PB0', 'PA0'),
 ('PC0', 'PB0', 'PA1'),
 ('PC0', 'PB1', 'PA0'),
 ('PC0E', 'PB1', 'PA1'),
 ('PC1', 'PB0', 'PA0'),
 ('PC1', 'PB0', 'PA1'),
 ('PC1', 'PB1', 'PA0'),
 ('PC1E', 'PB1', 'PA1'),
 ('PC2', 'PB0', 'PA0'),
 ('PC2', 'PB0E', 'PA1'),
 ('PC2', 'PB1', 'PA0E'),
 ('PC2E', 'PB1E', 'PA1E')]
</code></pre>

<p>On my timings it is the fastest approach using your data.</p>

<pre><code>In [37]: %%timeit
prod = list(product(*(list1, list2, list3)))
m(prod)
   ....: 
10000 loops, best of 3: 20.7 Âµs per loop

In [38]: %%timeit
prod = list(product(*(list1, list2, list3)))
for r, c in last_inds(prod).values():
    lst = list(prod[r])
    lst[c] += "E"
    prod[r] = tuple(lst)
   ....: 

100000 loops, best of 3: 12.2 Âµs per loop
</code></pre>

<p>Where m is:</p>

<pre><code>def m(inputlist):
    seensets = [set() for _ in inputlist[0]]
    outputlist = []
    for entry in reversed(inputlist):
        newentry = []
        for value, seen in zip(entry, seensets):
            newentry.append(value + 'E' if value not in seen else value)
            seen.add(value)
        outputlist.append(tuple(newentry))
    outputlist.reverse()
</code></pre>

python list