[Tutor] Looking for duplicates within a list

Sander Sweers sander.sweers at gmail.com
Fri Jun 11 16:46:25 CEST 2010


On 11 June 2010 15:57, Ken G. <beachkid at insightbb.com> wrote:
> 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.

If you do not have top keep the order of the number this will work.

>>> a = [1, 2, 3, 3, 4]
>>> counted = {}
>>> for n in a:
	if not n in counted:
		counted[n] = 1
	else:
		counted[n] += 1

>>> counted
{1: 1, 2: 1, 3: 2, 4: 1}

>>> for x, y in counted.items():
	if y > 1:
		print "Number %s was found %s times" % (x, y)
	else:
		print "Number %s was found %s time" % (x, y)

Number 1 was found 1 time
Number 2 was found 1 time
Number 3 was found 2 times
Number 4 was found 1 time

Greets
Sander


More information about the Tutor mailing list