Rita Sue and Bob too

Grégoire Dooms dooms at info.LESS.ucl.SPAM.ac.be
Fri Aug 20 08:04:01 EDT 2004


Cyrille Lavigne wrote:
> If you dont want them in order you should do:
> 
>>if "Rita" and "Sue" and "Bob" in list:
>>   print "They were found"
>>else:
>>   print "They are not in the list"

Wrong !
see:

In [6]: 'Rita' and 'Sue' and 'Bob' in ['Bob']
Out[6]: True

> 
> Otherwise:
> 
>>c,a=0,0
>>while c<len(list):
>>   if list[c]=="Rita":
>>       if list[c+1]=="Sue":
>>           if list[c+2]=="Bob":
>>               print "They were found"
>>               a=1
>>   c=c+1
>>if a!=1:
>>   print "they are not in the list"
> 
> but I'm sure there is a better way of doing this.
> 
This second piece of code searches list for the sequence 
['Rita','Sue','Bob'] in this order and without inserts.
It can be rewritten in a more pythonic way :

for i in range(len(l)):
     if l[i:i+3] == ['Rita','Sue','Bob']:
         print 'They were found'
         break
else:
     print 'They were not in the list'

--
Grégoire Dooms



More information about the Python-list mailing list