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

Maan Hamze mmhamze at pleiades.net
Sat Aug 25 15:03:30 EDT 2001


Sandy
you are dealing with sequences.  It is clear that sublst is NOT an element
of lst so it can not be in it and the result is 0.
Now, try:
>>> lst = [[1,2],2,3]
>>> sublst = [1,2]
>>> sublst in lst
1

Here sublst is an ***element*** of lst and the return is 1.  In the case you
give, sublst is not an element of the sequence lst.
To illustrate further:
>>> lst = [1,2,3]
>>> sublst = [1]
>>> sublst in lst
0
>>> sublst = 1
>>> sublst in lst
1
Maan

"Sandy Norton" <sandskyfly at hotmail.com> wrote in message
news:b03e80d.0108251027.508cb788 at posting.google.com...
> Please excuse me if this is a dumb comment that has been made before.
>
> Recently, I was rather surprised by the following behavior:
>
> Python 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on
> win32
> Type "copyright", "credits" or "license" for more information.
> >>> 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.
> 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
>
> >>> issublist([1,2], [1,2,3])
> 1
> >>> issublist([1,4], [1,2,3])
> 0
>
>
> regards,
>
>
> Sandy





More information about the Python-list mailing list