0
x=list(input()) 
y=list(input()) 
for a in x:
    if a in y:
        x.remove(a)
        y.remove(a)
print(x, y)

I can't get the exact answer for this code if I gave input like this

x = "lilly" 
y ="daliya"

The output must be

(l,l) (d, a, a) 

But it is

(i, l, l) (d, a, i, a)
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
  • 1
    Possible duplicate of [Removing from a list while iterating over it](https://stackoverflow.com/questions/6500888/removing-from-a-list-while-iterating-over-it) – Patrick Haugh May 02 '19 at 13:54
  • Possible duplicate of [Delete intersection between two lists](https://stackoverflow.com/questions/9331627/delete-intersection-between-two-lists) – Alex W May 02 '19 at 13:57
  • Start using print statement as debugger by printing for x/y each a variable. Then you can see in which order things are handled and figure it out yourself. – ZF007 May 02 '19 at 14:06
  • You just need to iterate on a copy of x via `x[:]` and you should not get this error anymore, check my answer below @Kumaresh ! – Devesh Kumar Singh May 02 '19 at 15:10

1 Answers1

2

Iterate on the copies of x, using list slicing arr[:] otherwise you are modifying the same list you are iterating on.

x=list('lilly')
y=list('daliya')
for a in x[:]:
    if a in y:
        x.remove(a)
        y.remove(a)
print(x, y)

The output will then be

['l', 'l'] ['d', 'a', 'a']
Devesh Kumar Singh
  • 19,767
  • 5
  • 18
  • 37