[Tutor] Looking for duplicates within a list
davea at ieee.org
Fri Jun 11 17:37:31 CEST 2010
Ken G. wrote:
> I have been working on this problem for several days and I am not
> making any progress. I have a group of 18 number, in ascending order,
> within a list. They ranged from 1 to 39. Some numbers are duplicated
> as much as three times or as few as none.
> I started with one list containing the numbers. For example, they are
> listed as like below:
> a = [1, 2, 3, 3, 4]
> I started off with using a loop:
> for j in range (0, 5):
> x = a # for example, 1
> How would I compare '1' with 2, 3, 3, 4?
> Do I need another duplicated list such as b = a and compare a with
> either b, b, b, b, b?
> Or do I compare a with a, a, a, a?
> In any event, if a number is listed more than once, I would like to
> know how many times, such as 2 or 3 times. For example, '3' is listed
> twice within a list.
I'm a bit surprised nobody has mentioned the obvious solution -- another
list of size 40, each of which represents the number of times a
particular number has appeared.
a = [1, 2, 3, 3, 4]
counts =  * 40
for item in a:
counts[item] += 1
Now, if you want to know how many times 3 appears, simply
The only downside to this is if the range of possible values is large,
or non-numeric. In either of those cases, go back to the default
More information about the Tutor