-1

I am trying to remove elements that have less than 4 characters in each element and it does work

with while-loop but I don't understand properly why it doesn't work with for-loop - please help, thank you

words = ['elephant','cat','dog','bird','lion']

    for i in range(len(words)):
        word = words[i]
        if len(word)<4:
            word.pop(i)
Wasif
  • 14,755
  • 3
  • 14
  • 34

2 Answers2

0

str does not have a .pop() method, also deletion while iteration is not supported instead try a list comprehension:

words = [x for x in words if len(x) < 4]

Still if you want to be verbose, then create new list, append items to it and assign a slice copy of new one to original:

words = ['elephant','cat','dog','bird','lion']
nw = []
for i in range(len(words)):
  word=words[i]
  if len(word)<4:
    nw.append(word)
words = nw[:]
print(words)
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Overall, your issue comes from:

word.pop(i)

You're trying to use pop on a string, not on your list. Your code is also not "Pythonic" since it is seemingly trying to use index values, when you can interate against your list without using that.

Your code can be simplified to make a new list with your desired words.

words = ['elephant','cat','dog','bird','lion']
output_words = []

for word in words:
    if len(word) < 4:
        pass
    else:
        output_words.append(word)
print(output_words)
dfundako
  • 8,022
  • 3
  • 18
  • 34