Python Error: IndexError: list index out of range(Python)

Question:

How come I’m getting this error?
I have 2 arrays a and b containing n integers. My main purpose is to remove a number from list a and b when it appears in both list.
My code:

for _ in range(int(input())):

    n=int(input())
    a=[*map(int, input().split())]
    b=[*map(int, input().split())]
    i=0
    j=0
    for i in a:
        for j in b:
            if a[i]==b[j]:
                a=a.pop(i)
                b=b.pop(j)

    m=0
    i=0
    for _ in range(len(a)):
        if len(a[i])!=len(b[i]):
            m+=2
        elif a[i]!=b[i]:
            m+=1
    print(m)

The error that i get:

    if a[i]==b[j]:
IndexError: list index out of range

Answers:

Modifying a list while iterating over it causes unexpected behavior. Your real issue is that you’re iterating over the elements in a and b but using i and j like they are indices.

You want to generate a new list of elements that appear in both lists.

a = [23, 45, 12, 8, 9, 2]
b = [2, 3, 4, 5, 6, 7, 8]
c = []

for x in a:
  for y in b:
    if x == y: c.append(x)

c
# [8, 2]

Now, you can remove these from your lists.

for z in c:
  a.remove(z)
  b.remove(z)

a
# [23, 45, 12, 9]

b
# [3, 4, 5, 6, 7]

At no point are we both iterating over and mutating a data structure at the same time.

Note that c could be generated with a list comprehension.

c = [x for x in a for y in b if x == y]
# [8, 2]

Or using an intersection of sets.

c = set(a) & set(b)
# {8, 2}
Answered By: Chris

If a new list will do, use a list comprehension:

c = [i for i in a if i not in b]

Otherwise, you can modify the lists themselves in a similar way:

a_copy = a[:]
a = [i for i in a if i not in b]
b = [i for i in b if i not in a_copy]
Answered By: Brent Pappas

As per my understanding from the user question

Seems like he need non-matching values

If that’s the case then you can make use of set method : symmetric_difference()

Code:

a = set([23, 45, 12, 8, 9, 2])
b = set([2, 3, 4, 5, 6, 7, 8])
result = a.symmetric_difference(b)
print(list(result))

If you want vice versa of both you can make use of this method : Set discard()

Refer these set methods it will be really helpful for you :
Link

Answered By: codeholic24
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.