Skip to content Skip to sidebar Skip to footer

Count Number Of Names In List In Python

i have one list wich has names in it: names = ['test','hallo','test'] uniquenames = ['test','hallo'] with set i get the uniquenames so the unique names are in a different list but

Solution 1:

You could use a dictionary:

names = ['test','hallo','test']
countnames = {}
for name in names:
    if name in countnames:
        countnames[name] += 1else:
        countnames[name] = 1print(countnames) # => {'test': 2, 'hallo': 1}

If you want to make it case-insensitive, use this:

names = ['test','hallo','test', 'HaLLo', 'tESt']
countnames = {}
for name in names:
    name = name.lower() # => to make'test' and 'Test' and 'TeST'...etc the same
    if name in countnames:
        countnames[name] += 1else:
        countnames[name] = 1print(countnames) # => {'test': 3, 'hallo': 2}

In case you want the keys to be the counts, use an array to store the names in:

names = ['test','hallo','test','name', 'HaLLo', 'tESt','name', 'Hi', 'hi', 'Name', 'once']
temp = {}
for name in names:
    name = name.lower()
    if name in temp:
        temp[name] += 1else:
        temp[name] = 1
countnames = {}
for key, value in temp.items():
    if value in countnames:
        countnames[value].append(key)
    else:
        countnames[value] = [key]
print(countnames) # => {3: ['test', 'name'], 2: ['hallo', 'hi'], 1: ['once']}

Solution 2:

Use Counter from collections:

>>> from collections import Counter
>>> Counter(names)
Counter({'test': 2, 'hallo': 1})

Also, for your example to work you should change names.count[i] for names.count(i) as count is a function.

Post a Comment for "Count Number Of Names In List In Python"