John Gordon
John Gordon

Reputation: 33343

Why does the 'in' operator recognize substrings but not sublists?

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

Answers (2)

pylang
pylang

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:

  • When data structure and element types are equivalent, in comparison is clear, e.g. a substring of a string.
  • When data structure and element types are not equivalent, in is ambiguous.

Let's look closer at this ambiguity.

Discussion

Given

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

are we comparing

  1. containers of elements (default)?
  2. just elements alone?

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

  1. Leave container + element comparisons to in
  2. Leave strict element comparisons to set()

Upvotes: 0

Back2Basics
Back2Basics

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

Related Questions