First of all, I want to review the function you already have:
def read_and_delete(x):
count = 0
i = 0
# for each word in list, store word in the "delete" variable
for delete in x:
# you are iterating over elements, but also using index
if x[i] != word_length: # if word not equals length
del x[i]
i += 1
return # exit from function
elif x[i] == word_length: # again, comparing a word and a number
count += 1
i += 1
return # exit from function
else: # never happens, because word is either
# equal or not, there is no other case
break # exit from loop
# if we actually visited the for loop (the list was not empty),
# this line would never be executed
print(len(list_of_words))
Next, how to fix it:
- If you want to iterate over all list, you should not use return or break (these are useful in other cases, thought).
- If you do want to remove elements from a list, you should do that a bit differently: How to remove list elements in a for loop in Python?
- To get length of the word (and any other string) you can use
len()
.
- Also, check the logic of your conditions.
To summarize, here's the fixed function (makes a new list):
def read_and_delete(x):
result = []
for word in x:
if len(word) != word_length:
result.append(word) # add word to the end of "result"
print(len(result))
As you can see, the loop is pretty simple now. So, you can rewrite it as a list comprehension:
# instead of function call
filtered_list = [word for word in list_of_words if len(word) != word_length]
print(len(filtered_list))
You can read that as:
[word # put each "word" into a list
for word in list_of_words # get them from "list_of_words"
if len(word) != word_length] # leave only those which length != "word_length"
Edit: fixed condition in the function.