0

I'm trying to make a script that filters out a long list of words and only keeps the elements that have the length specified by the user. For some reason though, it would delete just above half the elements in the array. So I made a new program with less elements in the array to test it out and the same thing happens.

array = ['0', '1', '2a', '3b', '4aa', '5bb', '6aaa', '7bbb', '8aaaa', '9bbbb']
wordlength = input('Input length you do not want to delete')
for each in range(9):
    try:
        if len(array[each]) > int(wordlength) or len(array[each]) < int(wordlength):
            array.pop(each)
            print('The word,',array[each],', has been deleted')
    except IndexError:
            print(array)

If it matters, in my main program there are 113809 elements .

berry
  • 43
  • 2
  • 3
    Don't modify a list as you iterate over it; you'll end up skipping elements and not getting the right results. Instead make a whole new list and rebind `array` to it, e.g. `array = [i for i in array if len(i) == int(wordlength)]`. – Samwise Mar 05 '22 at 16:44
  • Can you iterate over the indexes to `array` in reverse? If so, then the `pop()` method will not affect the indexes. – quamrana Mar 05 '22 at 16:48
  • @Samwise. I don't think that's the right duplicate. The OP is iterating by index. – quamrana Mar 05 '22 at 16:53
  • If you iterate by element it's iterating by index "under the covers" and gets tripped up in exactly the same way. :) – Samwise Mar 05 '22 at 17:57
  • @Samwise: Ok, yes of course. Still that leaves iterating by indexes in reverse with the ability to use `pop()` or `del`. – quamrana Mar 05 '22 at 18:14
  • Why build a habit of doing things the hard way (and a way that's prone to subtle bugs if you slip up slightly), though? – Samwise Mar 05 '22 at 18:20
  • Indeed. That's why I upvoted your first comment. – quamrana Mar 05 '22 at 19:58

0 Answers0