[Tutor] Simple way to compare Two lists

Kent Johnson kent37 at tds.net
Fri Aug 10 14:07:39 CEST 2007


Jaggo wrote:
> Hello!
> 
> I desperately need a simple way to compare whether any item of SmallList 
> is in BigList.
> 
> My current way,
> 
> def IsAPartOfList(SmallList,BigList)
> for item in SmallList:
>     if item in BigList:
>        return True
> return False
> 
> Takes up waay too much time to process.
> Can anyone think of any better way?
> 
> Usually, SmallList is generated using range(Long, Long+ ~300)
> BigList is usually of a few hundreds of long numbers.

Why not just check if if any item in BigList is in the range Long, Long+300?

for item in BigList:
   if Long < item <= Long+300:
     return True
return False

which (in Python 2.5) can be shortened to
return any(item in BigList if if Long < item <= Long+300)

If you really have to make the list, you will do better with a set, 
especially if the set can be reused over multiple calls.

bigSet = set(BigList)
return any(item for item in SmallList if item in BigList)

If speed is critical, you might see if it matters which list becomes the 
set and which is iterated.

Kent


More information about the Tutor mailing list