-1

I'm having trouble getting my code to run. Any idea what is wrong with my code?

from random import randint
a=[]
b=[]
dup_list=[]
nodup_list=[]
for n in range (0,10):
    a.append(randint(0,20))
    b.append(randint(0,20))
print a, "\n"
print b, "\n"

for m in range(0, len(a)-1):
    if a[m] in b:
        dup_list.append(a[m])
    else:
        nodup_list.append(a[m])

for o in range(0,len(b)-1):
    if b[o] in a:
        b.remove(b[o])
nodup_list.append(b)

print dup_list, "\n"
print nodup_list,"\n"

I keep getting the error: [5, 17, 11, 18, 11, 20, 7, 16, 14, 14]

[Traceback (most recent call last): File "/Users/Apple/Desktop/Python/python projects/practice_python/exercise14.py", line 29, in 5, 3, 7, 8, 11, 18, 14, 9, 6, 18]

if b[o] in a:

IndexError: list index out of range

Any ideas why?

naz115
  • 21
  • 3
  • 3
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – michaeldel Apr 12 '20 at 21:51
  • Because `o` is not a valid index for `b`. It is equal to or larger than the length of `b`. – mkrieger1 Apr 12 '20 at 21:52
  • 1
    Also, https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists – mkrieger1 Apr 12 '20 at 21:55

1 Answers1

0

It's recommended in the python documentation to create a new list instead of iterating while removing. The index is out of bounds because the list is shortened during iteration and so the index becomes greater than or equal to its size.

Garret
  • 1,137
  • 9
  • 17