<br><br><div class="gmail_quote">On Mon, May 4, 2009 at 3:01 PM, John O'Hagan <span dir="ltr"><<a href="mailto:mail@johnohagan.com">mail@johnohagan.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div class="im">On Mon, 4 May 2009, Matthias Gallé wrote:<br>
> Hi.<br>
><br>
> My problem is to replace all occurrences of a sublist with a new element.<br>
><br>
> Example:<br>
> Given ['a','c','a','c','c','g','a','c'] I want to replace all<br>
> occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).<br>
><br>
<br>
</div>li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']<br>
for i  in range(len(li)):<br>
    if li[i:i + 2] == ['a', 'c']:<br>
        li[i:i + 2] = ['6']<br>
<br>
HTH,<br>
<font color="#888888"><br>
John<br>
</font></blockquote></div><br>Beware that you are mutating the list you are iterating over. That could lead to some strange bugs (for instance if you replaced the deleted items with a longer sequence, the range(len(li)) would still go up to the original lenght).<br>
It is better to modify a new list instead. Eg you could append to a new list.<br><br>Francesco<br>