2

This might be a very elementary question and I should know this but how does the following line evaluate to true?

>>> '' in 'spam'
True

Why/How is the empty string/character in a non-empty string? I tried this in Idle for Python 2.7 and it's evaluating to true. I found this from the link to Automate the Boring Stuff chapter 6

12
  • 2
    print( 'spam'[:0]) or print(repr('spam'[:0])) might make it more obvious Commented Dec 1, 2015 at 23:36
  • 1
    another dupe stackoverflow.com/questions/27603885/… Commented Dec 1, 2015 at 23:37
  • 1
    @PadraicCunningham [][:0] == [] yet [] in [] is False. Similarly, list('spam')[:0] == [] but [] not in list('spam'). Commented Dec 1, 2015 at 23:43
  • 1
    @Two-BitAlchemist, list('spam')[:0] is accessing a list not the string, there is no empty list in the list, the list itself is empty. Commented Dec 1, 2015 at 23:45
  • 2
    @PadraicCunningham Yes, strings are great like that in Python. Sometimes they behave like a character and sometimes like a string. There's a broader conceptual question here, and perhaps the majority of mathematicians and programmers think one way; but it's not obvious, it's taught. A string is an ordered sequence of characters (uncontroversial). The empty string is in every string including itself (largely uncontroversial though I am balking at it now). I challenge you to think of another ordered sequence of literally anything where we think about the empty version of it this way. Commented Dec 2, 2015 at 0:10

1 Answer 1

3

Because the in operator is to test membership, and by that notion, the empty set is a subset of all other sets. To be consistent in that regard, the in operator was deliberately designed to act accordingly.

5.9 Comparisons

The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.