0

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
5
  • 8
    Modifying lists while iterating over them is a bad idea. Commented Sep 12, 2022 at 15:24
  • Also, you have two lists. Commented Sep 12, 2022 at 15:25
  • a.pop doesn't return a, don't guess. Commented Sep 12, 2022 at 15:26
  • I'm newbie, What do you think I should do? Thank you! Commented Sep 12, 2022 at 15:28
  • 1
    Also Python for loops iterate the elements of a list, not its indices - so i and j may not be valid indices of a and b. Commented Sep 12, 2022 at 15:28

3 Answers 3

0

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}
Sign up to request clarification or add additional context in comments.

Comments

0

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]

1 Comment

This offers a solution, but not an explanation of what was wrong or why this works.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.