Check with 'in' list
Py3: contains(), in list
x = [3, 7, , (5,)] # test membership with 'in' print(3 in x) #= True print(x.__contains__(7)) #= True # conditional control structures if not 2 in x: print('2 is missing') #= 2 is missing if 4 not in x: print('4 is missing') #= 2 is missing # 9 is nested in a list # not a direct member print(9 in x) #= False print( in x) #= True # single value tuples are (v,) # 5 is an integer, (5,) is a tuple containing 5 # test to match nested tuple print(5 in x) #= False print((5,) in x) #= True
Notes: Container class membership test
The list container class implements the contains() method which allows the 'in' statement to be used to check for membership of an item within the list. If an item is 'in' the list, then a True value is returned.
Nested elements are not matched by value. If a tuple is present with one or more constituent literals, then the match will be done with an exactly same tuple.
list.count(item) --> int
Count elements in list provides more than just a present or absent.
Py3: Count items
x = [1, 1, 5, 7] print(x.count(1)) #= 2 print(x.count(5)) #= 1 print(x.count(2)) #= 0
Notes: Presence, then counts
Count offers the next level of membership test. Just checking if a literal value is within a list does not offer insite into if it occurs repeatedly. Count allows occurrence statistics to be extracted for an element.
Working with text, to check for letters.
Py3: Counting within strings and lists
# string to test with txt = "python list" # is 't' present? # how many times does 't' appear? print('t' in txt) #= True print(txt.count('t')) #= 2 # list of words from text # does 't' match with words? # count times 't' matches with words words = txt.split() #= ['python', 'list'] print('t' in words) #= False print(words.count('t') #= 0 # list of letters from text # is 't' present? # how many times does 't' appear? letters = list(txt) #= ['p','y','t','h','o','n',' ','l','i','s','t'] print('t' in letters) #= True print(letters.count('t') #= 2
Notes: Membership of letters
The test for letters within a text is implemented through string objects. So directly checking for a letter in a string works. Once words are segmented into letters, the membership test for a single letter fails. On the list side of things, a single letter does not match a whole word, and so it fails.
Once the text is converted into a list of letters, the list methods take over. Now checking for a letter for membership within a list of letters is valid.