Reputation: 31
Trying to create a word counting function that will count how many words of a given length are in a list.
my_list =['full', 'hello', 'light', 'too', 'wise']
If I wanted to search that list for 4 letter words...I was thinking:
def word_count(list, length):
count = 0
if len(list) == 3: #I know this is wrong
#it's just an example of what I was thinking
count += 1
return count
Any help is appreciated!
Upvotes: 0
Views: 4174
Reputation: 2014
Try that, it's more Pythonic:
def word_count(word_list, word_length):
return len(filter(lambda x: len(x) == word_length, word_list))
Upvotes: 5
Reputation: 360
Is this what you want?
def countWordlen(lst):
count = 0
for i in lst: # loop over the items of the list
if len(i) == 3: # if the len the items (words) equals 3 increment count by 1
count = count + 1
return count
lst =['full', 'hello', 'light', 'too', 'wise']
countWordlen(lst)
OUT: 1
Upvotes: 2
Reputation: 2322
@Mbruh you were almost there,you just need to loop through the whole list like
my_list =['full', 'hello', 'light', 'too', 'wise']
def word_count(list, length):
count=0
for word in list:
if len(word)==length:
count=count+1
return count
word_count(my_list,4)
2
Upvotes: 2