# Remove integer from list when condition is met

3115 views
6

I am trying to remove an integer from a list when a condition is met. I have the following code:

``````def isHarshad(x):
x1 = str(x)
x2 = list(x1)
x3 = [int(i) for i in x2]
x4 = sum(x3)
if x%x4 == 0:
return True
else:
return False

y1 = []
for i in range(y):
y1.append(i+1)
for r in y1:
r.remove(y1)
return y1

``````

To which I receive the following error.

``````AttributeError: 'int' object has no attribute 'remove'
``````

I would like for when isHarshad returns false that this value is removed from the list.

`y1.remove(r)`.

10

You are writing opposite in second loop

``````for r in y1:
y1.remove(r) # You wrote r.remove(y1)
``````

posted this
4

y1 is your list and r is your integer in that list. You need to remove from the list.

posted this
11

Not the best code, but this works:

``````def isHarshad(x):
x1 = str(x)
x2 = list(x1)
x3 = [int(i) for i in x2]
x4 = sum(x3)
if x%x4 == 0:
return True
else:
return False

y1 = []
for i in range(y):
y1.append(i+1)
for r in y1:
print('r: %s; y1:%s' % (r, y1))
y1.remove(r)
return y1

if __name__ == "__main__":
print('Result for ithHarshad(13) = %s' % result
``````

posted this
0

Your code seems to be trying to remove the list from the integer. Swap your variable names in the loop as follows:

``````if not isHarshad(x):
y1.remove(r)
``````

I changed your condition to make it more pythonic: when comparing to Boolean values you don't have to write it explicitly. So in this case, if `isHarshad` returns True, the the `not` inverts it and the code below is not run, but when it returns false, it is inverted to True, and the item is removed.

posted this