1

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?

4 Answers4

0

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?

norbjd
  • 10,166
  • 4
  • 45
  • 80
0

The bug is happening because you are removing an element of the list x while you are iterating.

Bryan
  • 184
  • 1
  • 4
0

You don't have to iterate. Try this:

set(x)-set(y)
Omkar Sabade
  • 765
  • 3
  • 12
0

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

henrhoi
  • 76
  • 5