Rita Sue and Bob too

Jeremy Jones zanesdad at bellsouth.net
Thu Aug 19 22:17:37 EDT 2004


M. Clift wrote:

>Hi All,
>
>Can someone help. I promise I've looked how to do this but can't find a
>way...
>
>Ok, to find one name is easy
>
>if 'Bob' in list:
>    print "They were found"
>else:
>    print "They are not in list"
>
>But, how to I find a sequence in a list of unknown size? i.e. this sequence
>in list of other names and replace it with three others?
>
>'Rita','Sue','Bob'
>
>This is almost a nightly occurrence (my posting questions), but I am
>learning : )
>
>
>  
>
I'm sure someone else can come up with something more elegant, but 
here's a way you could do it:

 >>> names
['larry', 'curly', 'moe', 'shimp', 'rita', 'sue', 'bob', 'billy', 'scott']
 >>> for idx in range(len(names)):
...     if names[idx:idx + 3] == ['sue', 'bob', 'billy']:
...             print "found 'em at element", idx
...             break
...
found 'em at element 5
 >>>

Notice, this:
 >>> ['sue', 'bob', 'billy'] in names
False
 >>>
 returns false.  The reason is, I think, because the set ['sue', 'bob', 
'billy'] is not really a subset of ['larry', 'curly', 'moe', 'shimp', 
'rita', 'sue', 'bob', 'billy', 'scott'], even though the three names 
appear sequentially in both lists.  But, this:

 >>> names2
[['sue', 'bob', 'billy'], ['larry', 'curly', 'moe', 'shimp', 'rita', 
'sue', 'bob', 'billy', 'scott']]
 >>> ['sue', 'bob', 'billy'] in names2
True
 >>>
does "work" for the same reason that it doesn't work in the first 
example.  The list ['sue', 'bob', 'billy'] itself is part of the larger 
list, names2.

HTH,

Jeremy Jones




More information about the Python-list mailing list