Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading