[1, 2] in [1, 2, 3] returns 0?

Peter Hansen peter at engcorp.com
Sat Aug 25 21:35:04 CEST 2001


Sandy Norton wrote:
> 
> Recently, I was rather surprised by the following behavior:
> 
> >>> lst = [1,2,3]
> >>> sublst = [1,2]
> >>> sublst in lst
> 0
> 
> I am sure there's a good reason why it would be considered unpythonic
> for the above to return 1... I just can't get my puny brain to figure
> it out right now.

Well,

>>> lst = [ 1, [1, 2], 2, 3]
>>> sublst = [1,2]
>>> sublst in lst
1

Given the choice between the two, this one should be considered
less surprising.  Well, with 20-20 hindsight, anyway. :-)

> I guess a function such as issublist(sublst, lst) would be more
> appropriate:
> 
> >>> def issublist(sublst, lst):
>         for item in sublst:
>                 if item not in lst: return 0
>         return 1

The problem with something like this is that for someone
else a different definition might be more useful.

For example, your issublist() actually just tests whether
each of the individual elements in the sublst occur in the
list, but not necessary in the same order.  Perhaps a more
suitable name for that implementation would be:

  def allElementsAlsoIn(subset, set):

or something like that.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list