Reputation: 33343
Why is this true:
'bcd' in 'abcde'
But this is false:
[2,3,4] in [1,2,3,4,5]
These statements are conceptually identical, are they not? Does the in
operator have special rules for strings?
Upvotes: 4
Views: 133
Reputation: 44585
Review
Let's look at the left/right superset data structures and their elements:
| Example | Structure | Element |
|-----------------------------|-----------|---------|
| 'bcd' in 'abcde' | str | str |
| [0, 1, 2] in [0, 1, 2, 3] | list | int |
I suspect the principle is as follows:
in
comparison is clear, e.g. a substring of a string.in
is ambiguous. Let's look closer at this ambiguity.
Discussion
Given
[0, 1, 2] in [0, 1, 2, 3]
are we comparing
If using approach 2 where in
solely compares elements, then
[0, 1, 2] in [0, 1, 2, 3]
(0, 1, 2) in [0, 1, 2, 3]
{0, 1, 2} in [0, 1, 2, 3]
should each return True
since 0, 1, 2
are elements shared in left and right containers. Such comparisons disregard the container type. This approach limits in
, especially since element comparison can done with sets:
set([0, 1, 2]) < set([0, 1, 2, 3])
# True
set([0, 1, 2]).issubset([0, 1, 2, 3])
# True
Summary
in
set()
Upvotes: 0
Reputation: 7806
A list can be contained inside a list.
[[2, 3, 4], 2, 3, 4, 5]
in which iterating over the outer list one element at a time
[2,3,4] in [[2, 3, 4], 3, 4, 5]
gives you a True
value
There is no equivalent for a string for this type of situation.
You can make a new type by subclassing list and changing the __contains__
as @hpaulj pointed out.
But here are some questions before you begin?
How many times would you expect to find [2,3,4] in this?
[[2, 3, 4], 2, 3, 4, 5]
or this
[[2,3,4], [2],[3],[4],5]
Upvotes: 4