### Thread: how to count chars in list

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2004
Posts
57
Rep Power
15

#### how to count chars in list

Hi all

list [ abcttraadezzreyeuw]
now how can i count the number of each characters
ie.. 3a's 2t's and on

Thanks
2. First off, the list should be

list = ['a', 'b', 'c', ...]
to be a list of characters. What you wrote down, the interpreter understands as a variable as index to the list, and since you did not declare it, it won't work.

You could have another list containing all letters, and then dynamically compare two lists to see which and how many of the elements in list 1 match the letters of the alphabet in list 2.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2001
Location
Houston, TX
Posts
383
Rep Power
17
So is this a list of individual characters or a string or a list of strings?

The basic code is:
Code:
```L = ['a', 'bc', 'def', 'aa', 'bcbc']
s = ''.join(L)
charFreqs = {}
for char in s:
if char in charFreqs:
charFreqs[char] += 1
else:
charFreqs[char] = 1```
4. Another simple solution, this time using the count() method.

Code:
```>>> sequence = 'Hello again lucky!'
>>>
>>> counters = {}
>>>
>>> for character in sequence:
...     if character not in counters:
...         counters[character] = sequence.count(character)
...
>>> counters
{'a': 2, ' ': 2, 'c': 1, 'e': 1, 'g': 1, 'i': 1, 'H': 1, 'k': 1, 'l': 3, 'o': 1, 'n': 1, '!': 1, 'u': 1, 'y': 1}
>>>```
In the example sequence is a string, but since Python treats iteration over Strings, Lists and Tuples in same way it "shouldn't" matter which data-type is used here.

However, Tuples don't have a count() method, which limits you to using either a String or a List if you want to do it this way .

Take care,

Mark.