# [Tutor] Replace sequence in list - looking for direction

peter hodgson imputerate at puteracy.com
Sat Sep 6 09:58:47 CEST 2008

```greetings, fellow ventriloquists;

the exchanges on this list are great tutorials; sometimes i don't quite
get the finer points; like here:

On Mon, Jun 16, 2008 at 10:41 AM, GTXY20 <gtxy20 at gmail.com> wrote:
> Let's say I have a list like the following:
>
> a = ['a1','a2','a3','a4','a5','a6']
>
> and then I have dictionary like the following:
>
> b = {'a1,a2,a3':'super'}
>
> I need some direction and thoughts on how I might seach the list for the
> string (the key in dict b) sequence in list a and replace the occurance with
> the value from dict b. At the end I would like to have list a represented
> as:
>
> a = ['super', 'a4', 'a5', 'a6']

the solution:
From: Tiago Saboga <tiagosaboga at gmail.com>

The following works for your example. I assume the values in the a
list are unique.

for key in b:
keylist = key.split(',')
if keylist < a:
i = a.index(keylist[0])
print a[:i] + [b[key]] + a[i+len(keylist):]

---------------------
but this works, too;

>>> a = ['a1','a2','a3','a4','a5','a6']
>>> b = {'a1,a2,a3':'super'}
>>> for key in b:
...     keylist = key.split(',')
...     i = a.index(keylist[0])
...     print [b[key]] + a[i+len(keylist):]
...
['super', 'a4', 'a5', 'a6']
-----------------------

now, i get it, mostly; but keylist being shorter than the list "a"

>>> keylist < a
True

doesn't seem relevant, unless the 'for' statement were to go on and on;

and if a[:i] = zilch:

>>> for key in b:
...     keylist = key.split(',')
...     if keylist < a:             # DOES THIS MEAN LENGTH?
...         i = a.index(keylist[0]) # a[index of first item in the key == 0];
...         print a[:i]             # a[:0] == pre-first item == None;
...
[]

then why bother with that part?

---------------------------------

finally, how might the code handle a dictionary with more than one item?

since i figured the line
if keylist < a:
might be part of some kind of iteration, say, until all of the items in
"a" had been replaced by dictionary values,

this is as far as i got:

>>> a = ['a','b','c','d','e','f']
>>> b = {'a,b':'firstval', 'c,d':'secondval'}
>>> for key in b:
...     keylist = key.split(',')
...     if keylist < a:
...         i = a.index(keylist[0])
...         print a[:i] + [b[key]] + a[i+len(keylist):]
...
['firstval', 'c', 'd', 'e', 'f']

but 'secondval' did not replace 'c' and 'd' in "a";

what am i missing? thanks, imputerate
```