I am trying to iterate through a list checking every string in the list for a character.
test = [str(i) for i in range(100)]
for i in test:
if '0' or '4' or '6' or '8' in str(i):
test.remove(i)
I thought this would be fine but, the list is this after:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
Where the ‘2’ is removed but, the ’41’ is not? I’ve noticed its only even numbers but, don’t know why.
You have two problems. First, this
ifstatement is always taken.Because the string
0is a non-zero-length string, and is thereforeTrue.0or4is0and thereforeTrue. The rest of the statement doesn’t matter.I expect you actually wanted to test whether each of those digits was in the string representation of the integer. As you have it written now, you are only testing whether
8is in the string, and that’s not even getting tested because the expression evaluates toTruebefore it even gets there. Something like this would work:By the way,
str(i)is superfluous because your list is already a list of strings.The other problem is that you are deleting items from the list you are iterating over. So, here’s what happens:
0, is removed, because yourifstatement is always taken.1, becomes the first item, because you removed0.forloop goes on to the second item, which is now2.In other words, because you deleted
0,1is never tested. Thus, every other item (all the even numbers) are removed.The easiest way to avoid this in your code is to iterate over a copy of the list: