Question

In Python, asking if a substring exists in a string is pretty straightforward:

>>> their_string = 'abracadabra'
>>> our_string = 'cad'
>>> our_string in their_string
True

However, checking if these same characters are "in" a list fails:

>>> ours, theirs = map(list, [our_string, their_string])
>>> ours in theirs
False
>>> ours, theirs = map(tuple, [our_string, their_string])
>>> ours in theirs
False

I wasn't able to find any obvious reason why checking for elements "in" an ordered (even immutable) iterable would behave differently than a different type of ordered, immutable iterable.

Was it helpful?

Solution

For container types such as lists and tuples, x in container checks if x is an item in the container. Thus with ours in theirs, Python checks if ours is an item in theirs and finds that it is False.

Remember that a list could contain a list. (e.g [['a','b','c'], ...])

>>> ours = ['a','b','c']    
>>> theirs = [['a','b','c'], 1, 2]    
>>> ours in theirs
True

OTHER TIPS

Are you looking to see if 'cad' is in any of the strings in a list of strings? That would like something like:

stringsToSearch = ['blah', 'foo', 'bar', 'abracadabra']
if any('cad' in s for s in stringsToSearch):
    # 'cad' was in at least one string in the list
else:
    # none of the strings in the list contain 'cad'

From the Python documentation, https://docs.python.org/2/library/stdtypes.html for sequences:

x in s  True if an item of s is equal to x, else False  (1)
x not in s  False if an item of s is equal to x, else True  (1)

(1) When s is a string or Unicode string object the in and not in operations act like a substring test.

For user defined classes, the __contains__ method implements this in test. list and tuple implement the basic notion. string has the added notion of 'substring'. string is a special case among the basic sequences.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top