Does not delete from the list

advertisements

Im working with the next code:

for u in G:
    if u.count('L')>1:
        while (u in G)==True:
            G.remove(u)
print G

Where G is a list of strings with the letters O,A and L. The problem is that, inclusive when u.count('L') is greater than 1, the object u doesn't goes from the list. How can i repair this? Thanks.

[Edit] For a example of the list I'm using, here it is: https://www.dropbox.com/s/qiv2jq4xlg0d5sg/list.txt


You seem to be trying to remove words that contain more than one consecutive 'L' in them.

input: ['ALL', 'APPLE', 'LLAMA', 'LAX', 'PALLOR']

output: ['APPLE', 'LAX']

Here are some approaches:

List Comprehension

lyst[:] = [word for word in lyst if 'LL' not in word]

(the [:] part says to put the new list in the same place the old one was. It's not very important for small lists, but makes it look like you know what you're doing.)

Filter

lyst = filter(lambda word: 'LL' not in word, lyst)

(You could do the [:] trick again with filter in Python 2, but in Python 3 filter doesn't return a list, so I left it out.)

For loop

How not to do it:

for i, word in enumerate(lyst):
  if 'LL' in word:
    del lyst[i]

Why not? It seems to work with the above list, but look at the indices that are being nuked:

>>> lyst = ['ALL', 'APPLE', 'LLAMA', 'LAX', 'PALLOR']
>>> for i,w in enumerate(lyst):
...   print i,w
...   if 'LL' in w:
...     del lyst[i]
...
0 ALL
1 LLAMA
2 PALLOR

That's no good! "LLAMA"'s index didn't start out as 1. We can break this algorithm by changing the input list:

>>> lyst=['APPLE', 'ALL', 'LLAMA', 'LAX', 'PALLOR']
>>> for i,w in enumerate(lyst):
...   print i,w
...   if 'LL' in w:
...     del lyst[i]
...
0 APPLE
1 ALL
2 LAX
3 PALLOR
>>> lyst
['APPLE', 'LLAMA', 'LAX']

The list comprehension or filter approaches are probably the best, but if you really prefer to write out your loops, you must go in reverse to avoid the indices changing out from under you:

>>> for i, w in reversed(list(enumerate(lyst))):
...   print i,w
...   if 'LL' in w:
...     del lyst[i]
...
4 PALLOR
3 LAX
2 LLAMA
1 ALL
0 APPLE
>>> lyst
['APPLE', 'LAX']