0

I have the below code. It's working except when I have a duplicate that repeats 3 or more times, the program is considering that element as a new number and displaying it twice. How to fix this issue?

import collections
mylist = [1,2,3,4,5,5,6,7,7,7,8,9]
i = 0
count = 0


for i in range(len(mylist)):
    print1 = mylist.count(mylist[i])
    if print1 > 1:

        print("Duplicate Element: " , mylist[i])
        print("It is repeated " , print1, "times")
        mylist.remove(mylist[i])
        count += 1
        i += 1

The output I am getting is

Duplicate Element:  5
It is repeated  2 times
Duplicate Element:  7
It is repeated  3 times
Duplicate Element:  7
It is repeated  2 times
Traceback (most recent call last):
  File "C:/Users/sanantha/Documents/Python/Lab6/task3.py", line 10, in <module>
    print1 = mylist.count(mylist[i])
IndexError: list index out of range

How to fix this?

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
shegiggles
  • 31
  • 1
  • 3
  • 2
    Don't modify a list at the same time you're looping over its contents. `mylist.remove` is making the list shorter, but you're still looping over the original length. – John Gordon Feb 19 '16 at 16:12
  • Possible duplicate: http://stackoverflow.com/questions/30565759/get-unique-values-in-list-of-lists-in-python – F. Müller Feb 19 '16 at 17:52

4 Answers4

0

Here is another way how you can proceed, using itertools.groupby:

from itertools import groupby

print(*["Duplicate element: {}. It is repeated {} times."
         .format(k, len(list(group))) for k, group in groupby(mylist)
         if len(list(group)) > 1],
         sep='\n')

Output:

Duplicate element: 5. It is repeated 2 times.
Duplicate element: 7. It is repeated 3 times.
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
0

Use the collections.Counter, it was built for this:

from collections import Counter

mylist = [1,2,3,4,5,5,6,7,7,7,8,9]
for value, repeats in Counter(mylist).items():
    if repeats > 1:
        print("Value {} repeats {} times".format(value, repeats)
Oin
  • 6,951
  • 2
  • 31
  • 55
0

You're code need just a fix. The best approach to this way is using sets

mylist = [1,2,3,4,5,5,6,7,7,7,8,9]

for i in set(mylist):
    count = mylist.count(i)
    if count > 1:
        print('Duplicate Element: %i' % i)
        print('It is repeated  %i times' % count)
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
0

Index out of range means that you are trying to access an element which is out of bounds within the data structure.

E.g. you have an array [1,2,3,4] (index: 0,1,2,3) - you perform a remove on index 1. This will give you an array of [1,3,4] (index: 0,1,2). Now trying to access index 3 will result in a index out of range exception since it no longer exists.

codex
  • 45
  • 6