0

I am new to python and programming in general and currently learning the fundamentals. In the script below I am trying to check the number of letters in each list element and delete ones with five and more letters. I am using for-loop to achieve this but an issue is occurring because of the change in the number of list elements which does not corresponds to the for-loop range considered initially. I tried to let the range vary itself but I errors are still obtained.

# -*- coding: utf-8 -*-

magicians =['alice','david','carolina']

def counter(word):
    x= sum (c != ' ' for c in word)
    return x

print magicians
for i in range (0,3):
        magicians[i]=magicians[i].title()
print magicians
q=
Y=range (0,q)

for i in Y:
    x= counter(magicians[i])
    print x    
    if x<=5:
        print 'this component will be deleted:', magicians[i]
        del magicians[i]
        q=q-1
        Y=range (0,q)
print magicians

Thank you

2 Answers2

0

The main problem with your code is that the Y = ... within the loop does not have an effect on the Y in for i in Y.

for i in Y:
    ...
        Y=range (0,q)

You could change your code to use a while loop, and manage the current index and the maximum index manually, but this is very prone to error:

i = 0
while i < q:
    x= counter(magicians[i])
    if x<=5:
        print 'this component will be deleted:', magicians[i]
        del magicians[i]
        q=q-1
    else:
        i += 1

Instead of deleting elements from a list while iterating the same list, it is much better practice to populate a second list, holding only the elements you want to keep, e.g. using a list comprehension:

good_magicians = [m for m in magicians if counter(m) > 5]
tobias_k
  • 81,265
  • 12
  • 120
  • 179
-1

There is a sophisticated answer to your problem in this post: Remove items from a list while iterating

The easiest one is to create a new list only containing the elements you actually want.

Community
  • 1
  • 1
c0delama
  • 663
  • 6
  • 9