Code
def removeEven(List):
for x in List:
if x % 2 == 0:
List.remove(x)
return List
print(removeEven([18, 106, -158, -124, 199, -28, -68, -91, 46, -190, 63, -30, 142, -36, -162, -121, 14, -192, -143, -57, -59, -129, -146, -76, -186, -84, 70, 19, -13, -12, -5, 179, -191, -43, 160, -156, 105, 104, 93, -188, -184, -197, -136, -35, 16]))
Output
[106, -124, 199, -68, -91, -190, 63, 142, -162, -121, -192, -143, -57, -59, -129, -76, -84, 19, -13, -5, 179, -191, -43, -156, 105, 93, -184, -197, -35]
Code
def removeEven(List):
result = []
for x in List:
if x % 2 != 0:
result.append(x)
return result
Output
[199, -91, 63, -121, -143, -57, -59, -129, 19, -13, -5, 179, -191, -43, 105, 93, -197, -35]
I came across this strange behavior. I am writing a simple function to remove even numbers from a list but when I modify the list that is passed as an argument and return it I get a weird output. Does anyone know what the reason is?
Please note i am not looking for answer to this problem it is easy to google but just explanation about why the output is different when i don't create a new list and return it.