I wrote the following python code in jupiter-notebook:
x=['b','x','a']
y=['b','x','a']
for i in x:
if i in y:
x.remove(i)
print (x)
I expected an empty list, but the output was ['x']. What is wrong in the code?
I wrote the following python code in jupiter-notebook:
x=['b','x','a']
y=['b','x','a']
for i in x:
if i in y:
x.remove(i)
print (x)
I expected an empty list, but the output was ['x']. What is wrong in the code?
You are getting this behavior because you are removing items in the list x
while iterating on it.
To have the result you expect (an empty list), you should use a list comprehension :
x = [i for i in x if i not in y]
print(x) # prints []
Check this StackOverflow question on the same subject : How to remove items from a list while iterating?
The bug is happening because you are removing an element of the list x
while you are iterating.
Here you can use the filter-function, as such
x = list(filter(lambda element: element not in y, x))
See http://book.pythontips.com/en/latest/map_filter.html#filter