Reputation: 321
I'm creating a program in which the user enters a list of names and the computer then prints it out any names which have been duplicated. The code I have so far is:
names = []
final = []
enter = raw_input('Enter the name')
while enter != 'exit':
names.append(enter)
enter = raw_input('Enter the name')
for i in names:
for a in (names):
a = i + 1
if a == i:
final.append(i)
print final
I get an error when it reaches
a = i + 1
How can I fix this?
Upvotes: 0
Views: 48
Reputation: 50600
You can find duplicates by doing this (in place of your for
loops)
print set(x for x in names if names.count(x) > 1)
This is going to return a set
of values that appears in the names
variable more than one time.
names = []
final = []
enter = raw_input('Enter the name')
while enter != 'exit':
names.append(enter)
enter = raw_input('Enter the name')
print(set(x for x in names if names.count(x) > 1))
Output:
Enter the nameAndy
Enter the nameAndy
Enter the nameAndy
Enter the nameBob
Enter the nameGeorge
Enter the nameAndy
Enter the nameBob
Enter the nameexit
set(['Bob', 'Andy'])
Bob
and Andy
were entered more than once. George was not, thus doesn't appear in the set.
Upvotes: 2
Reputation: 107347
You can not assign to a string object, if you want to get the strings that have duplicates in your list you better to use collections.Counter
which returns a Counter object, then you can extract the names that those count is more than one.
from collections import Counter
for name,cnt in Counter(names):
if cnt>1:
print name
Upvotes: 1