2

I have a list with lists looking like this:

c = [[1,0,1], [2,3,1], [0,0,0]]

I made a function toss_non_G2(potential_list) looking like this:

def  toss_non_G2(potential_list):
    for list in potential_list:
        if any(x not in [0,1] for x in list):
            potential_list.remove(list)
    return potential_list

I tried it out:

print(toss_non_G2(c))
>>> [[1, 0, 1], [0, 0, 0]]

Just like I expected. But, then I tested it out on something a bit more complicated, and hence the issue:

import numpy as np
from scipy.linalg import solve

A = [[0.8760162 , 0.0571752 , 0.43403856], [0.04730946, 0.56278686, 0.05767958], [0.95880316, 0.9595227 , 0.02226051]]

b_list = [[1, 0, 1], [1, 1, 1]]

x_list = list()
for b in b_list:
    x = solve(A, b)
    x_list.append(x)

print(toss_non_G2(x_list))
>>> [array([-0.52792558,  1.49611693,  3.17236923])]

In this case I expected an empty list. Why isn't all the lists with any values differing from 0 or 1, as by the if-statement, being removed? Does it has something to do with the list being a numpy-array?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
RoyM
  • 735
  • 3
  • 14

1 Answers1

1

Modifying a list you are iterating on is a bad idea.

Instead of removing arrays that do not satisfy your condition, simply return a list whose arrays satisfy your condition:

def  toss_non_G2(potential_list):
    return [l for l in potential_list if all(x in [0,1] for x in l)]

If necessary, see the documentation for all().

sentence
  • 8,213
  • 4
  • 31
  • 40
  • That's odd. There was an accepted answer here already. And another one. Now yours is the only one. But thanks for your answer also, it's basically the same as given by the others. – RoyM Apr 01 '19 at 02:14