On 01/05/2013 01: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) > > Moreover, for the lists of strings the following for-loop gives correct > results when the above reduce expression doesn't. > > isSublist = True > for i in lst1: > isSublist = isSublist and (i in lst2) > if not isSublist: > isSublist = False > break > > > Can someone help me understand why? > > Asim reduce only makes sense if the value you're reducing to is of the same type as the elements of the list you're iterating over. Since your lambda expression returns a boolean (True or False), it'll seem to work on some lists of ints. That's just a coincidence since the bools are compatible with ints, and maybe you've got a 0 or 1 in the list. But if your list has only strings, then True will never be that list.
If you're trying to make a faster loop, then I suggest you look into set differences. Turn both lists into sets, and subtract them. Something like (untested): result = not bool( set(lst1) - set(lst2) ) -- DaveA -- http://mail.python.org/mailman/listinfo/python-list