going thru a tutorial on python lists,I tried to write a python function which counts the number of occurrences of words that start with a specific letter
def count_occurrences(p,letter):
count = 0
for elem in p:
if elem[0]==letter:
count = count+1
return count
>>>count_occurrences(['damon','jim','dennis'],'d')
2
>>>count_occurrences(['damon','jim'],'d')
1
>>>count_occurrences([],'d')
0
but, if I input a list containing the wrong types,say [1,2,3] ,it will throw a TypeError:'int' object is unsubscriptable since the code elem[0] is called on an int.
So,how do I handle this? should I use a try : except block or is there another way?