find sublist inside list
John O'Hagan
mail at johnohagan.com
Mon May 4 09:01:36 EDT 2009
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
More information about the Python-list
mailing list