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

Alan Gauld alan.gauld at btinternet.com
Sat Sep 6 16:10:42 CEST 2008

```"peter hodgson" <imputerate at puteracy.com> wrote

>> for key in b:
>>    keylist = key.split(',')
>>    if keylist < a:
>>        i = a.index(keylist[0])
>>        print a[:i] + [b[key]] + a[i+len(keylist):]
>
> now, i get it, mostly; but keylist being shorter than the list "a"
>
>>>> keylist < a
> True

This is not testing the length it is testing the contents.

>>> a = ['a','c','e']
>>> b = ['b','d','f']
>>> a<b
True
>>> b<a
False

It sees that 'a' < 'b' so returns True for a<b but
since 'b' is not less than 'a' it returns false for b<a
Now consider more closely aligned examples:

>>> c = ['a','b','c']
>>> c<a
True

Here the a's are equal so it checks the second element
and finds b < c so c<a is true

Finally for unequal length strings

>>> d = ['a','c']
>>> d<a
True
>>> d<c
False
>>>

So d winds over a since the third element not existing
is taken to be lower valued than it existing. But the
character values in d<c a still win out regardless of length.

Does that make sense?

So in the original program

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

It is checking that it will find a valid index in the i assignment.
Having said that I'm not sure the check is fully effective since
I have a feeling it may fail for duplicated instances of the first
more complex than just length.

And finally the a{:i]  part is to cover the case where the
index i is greater than 0. So we retain the initial values up
to the matching key.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

```