2

I am new to Python. I have a list, with duplicate entries. Is their any way you can count the number of UNIQUE strings? Regards,

input1 = input("Name ")
input2 = []
input2.append(input1)
while input1:
  input1 = input("Name ")
  input2.append(input1)

I just want to print out the number of unique names entered. Thanks!

R337
  • 81
  • 1
  • 6

2 Answers2

3

How about this:

len(set(input2))

len(set(n[5:] for n in input2))
Eastsun
  • 18,526
  • 6
  • 57
  • 81
  • I've tried using that, but it didn't work. `Name: Nick Name: Sam Name: Nick Name: Rob Name #whitespace 4 #len(set(input2)) ['Nick', 'Sam', 'Nick', 'Rob', '']` – R337 Sep 06 '13 at 07:28
  • It gives a length of four because it counts the empty string at the end of your list as a unique element. Apply the changes suggested in my comments to your question and the problem will go away. – Steven Rumbalski Sep 06 '13 at 07:32
  • 1
    What is `len(set(n[5:] for n in input2))` supposed to do? – Steven Rumbalski Sep 06 '13 at 07:39
2

We can use Counter from collections

>>> a=['Jack','Jill','Jack']
>>> from collections import Counter
>>> myDict=Counter(a);
>>> myDict


Counter({'Jack': 2, 'Jill': 1})

Then we can use myDict as a dictionary only

Koustav Ghosal
  • 504
  • 1
  • 5
  • 16