find sublist inside list
John O'Hagan
mail at johnohagan.com
Mon May 4 13:33:40 EDT 2009
On Mon, 4 May 2009, Francesco Guerrieri wrote:
> On Mon, May 4, 2009 at 3:01 PM, John O'Hagan <mail at johnohagan.com> wrote:
> > On Mon, 4 May 2009, Matthias Gallé wrote:
> > > Hi.
> > >
> > > My problem is to replace all occurrences of a sublist with a new
> > > element.
> > >
> > > Example:
> > > Given ['a','c','a','c','c','g','a','c'] I want to replace all
> > > occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).
> >
> > li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
> > for i in range(len(li)):
> > if li[i:i + 2] == ['a', 'c']:
> > li[i:i + 2] = ['6']
> >
> > HTH,
> >
> > John
>
> 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).
> It is better to modify a new list instead. Eg you could append to a new
> list.
[...]
Quite right, while it happens to work in this particular example, as you and
MRAB point out, it's generally dangerous (and in fact this one silently and
uselessly iterates over the last couple of indexes which no longer exist); a
new list could be created like this:
index=0
newli=[]
while index<len(li):
if li[index:index+2]==['a', 'c']:
newli.append(6)
index += 2
else:
newli.append(li[index])
index += 1
Regards,
John
More information about the Python-list
mailing list