-1
a = [[' 0 ', '*X*', '*Y*', '*Z*'], [' 0 ', '*X*', '*Y*', '*Z*'], [' 0 ', '*X*', '*Y*', '*Z*']]

for i in a:
    for j in i:
        if '*' in j:
            i.remove(j)


for i in range(len(a)):
    for j in range(len(a[i])):
        if '*' in a[i][j]:
            del a[i][j]

I try to delete the item contain star in the list, but the first loop will give me out of range error, and the second loop will still have y does not delete, how do I fix the problem? Thank you very much

James Dewes
  • 387
  • 4
  • 22
elfa26
  • 11
  • 6
  • 1
    Looks like a duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Yann Vernier May 31 '18 at 07:14
  • 3
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Mr. T May 31 '18 at 07:14

3 Answers3

4

You're mutating the array while iterating over it. Don't do that. Instead use list comprehensions (to be Pythonic):

a = [
    [' 0 ', '*X*', '*Y*', '*Z*'],
    [' 0 ', '*X*', '*Y*', '*Z*'],
    [' 0 ', '*X*', '*Y*', '*Z*'],
]

a = [[e for e in l if '*' not in e] for l in a]

# >>> a
# [[' 0 '], [' 0 '], [' 0 ']]

If for some reason you still need to mutate a (i.e. keep it referencing the same list object), you can do a[:] = ... instead of a = ....

AKX
  • 152,115
  • 15
  • 115
  • 172
0

Iterating over the same list and change its values making issues for you.

for i in a[:]:
    #      ^  Help to iterate over a copy of a 
    for j in i[:]:
        #      ^ Help to iterate over a copy of i
        if '*' in j:
            i.remove(j)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0

A list comprehension can return the results that you are looking for:

a = [[i] for j in a for i in j if '*' not in i]
print(a)

Here is your output:

[[' 0 '], [' 0 '], [' 0 ']]

We essentially run a for loop. So [i] in our list comprehension is the value that we will be adding to the list. The value will be a nested list in it of itself which you have in your code. That is why we put brackets around it. For as you know is simply each of the nested lists in a. And then we run a conditional test 'if '*' not in i, which will add the value to the list if the placeholder is not there. That should resolve your issue, and greatly simplifies your code.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27