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)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 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
  • 20,259
  • 5
  • 21
  • 40