python - String vs list membership check -
so i'm wondering why this:
'alpha' in 'alphanumeric'
is true
,
list('alpha') in list('alphanumeric')
is false
.
why x in s
succeed when x
substring of s
, x in l
doesn't when x
sublist of l
?
when use list
function iterable, new list object created elements iterable individual elements in list.
in case, strings valid python iterables, so
>>> list('alpha') ['a', 'l', 'p', 'h', 'a'] >>> list('alphanumeric') ['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']
so, checking if 1 list sublist of list.
in python strings have in
operator check if 1 string part of string. other collections, can use individual members. quoting documentation,
the operators
in
,not in
test collection membership.x in s
evaluates true ifx
member of collections
, , false otherwise.x not in s
returns negation ofx in s
. collection membership test has traditionally been bound sequences; object member of collection if collection sequence , contains element equal object. however, make sense many other object types support membership tests without being sequence. in particular, dictionaries (for keys) , sets support membership testing.for list , tuple types,
x in y
true if , if there exists indexi
suchx == y[i]
true.for unicode , string types,
x in y
true if , ifx
substring ofy
. equivalent testy.find(x) != -1
. note,x
,y
need not same type; consequently,u'ab'
in'abc'
returntrue
. empty strings considered substring of other string,""
in"abc"
returntrue
.
Comments
Post a Comment