reduce expression to test sublist

Terry Reedy tjreedy at udel.edu
Sat Jan 5 22:55:59 CET 2013


On 1/5/2013 1:25 PM, Asim wrote:
> Hi All
>
> The following reduce expression checks if every element of list lst1
> is present in list lst2.  It works as expected for integer lists but
> for lists of strings, it always returns False.
>
> reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)

reduce(lambda x, y: x and (y in lst2), lst1, True)

would work, but as other have said, you want to stops at the first 
False, which all() does, and if lst2 is a list of hashable items, x in 
set for O(1) rather than O(n) check.


> Moreover, for the lists of strings the following for-loop gives
> correct results when the above reduce expression doesn't.

You should include data for testing.

>
> isSublist = True
 > for i in lst1:
 >   isSublist = isSublist and (i in> lst2)

If isSublist remains True, there is no need to rebind it

 >   if not isSublist:
 >     isSublist = False

Setting isSublist False when it is False is redundant.

>     break

Taking into account the comments:

def is_sublist(a, b):
   b = set(b)  # optional, depending on contents
   for item in a:
     if item not in b:
       return False
   else:  # not needed because return above
     return True

The code for all() is similar, except that all takes an iterable, so 
that the testing is done as part of the input iterable.

def all(iterable):
   it = iter(iterable):
   for item in it:
     if not it:
       return False:
   else:
     return True

def issublist(a, b):
   b = set(b)
   return all(item in b for item in a)

-- 
Terry Jan Reedy




More information about the Python-list mailing list