Python 3.x : using a list, if a letter isn't in that list, add it. otherwise, increment the value by 1
<p>so this is what I'm doing: I'm pulling up a file and having the program read it. Every time it encounters a letter, it'll add the letter to list1 and add '1' to list2. Every time it encounters a letter in list1, it'll increment list2 by 1. </p>

<pre><code>txt = open("Nameoffile.txt")
wordcount = 0
Charcount = 0
letterlist = [] #list 1
lettercount = [] #list 2

for words in txt:
    print(words)
    for letters in words:
        if letters not in letterlist:
           letterlist.append(letters)
           lettercount[letters] = 1
        else:
           lettercount[letters] += 1

        Charcount += 1
        print(letters)
        if letters == ' ':
           wordcount += 1
        if letters == '.':
           wordcount += 1
        if letters == '\n':
           Charcount -= 1
           wordcount += 1

#down here it would print the results
</code></pre>

<p>the problem I'm running into is that when running this, I get the following error:
line 14, lettercount[letters] = 1
TypeError: list indices must be integers or slices, not str</p>

<p>I assumed I could get away with stating that at list[letter] set that value to a number, but it isn't liking it. any possible hints on what to do?</p>

<p>That line of your function essentially tries to do something like this:</p>

<pre><code>lettercount['a'] += 1
</code></pre>

<p>which doesn't really make any sense. Lists are ordered collections and are only accessible via numerical index, which is why you get an error telling you that an integer is required (not a string). As the other answers mentioned, you really want to store the count for each letter in a dict. The Python standard library provides a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> dict subclass which is actually perfect for your needs - it'll count the characters for you and make it easy to remove duplicates:</p>

<pre><code>import collections

lettercount = collections.Counter(yourtext)

letterlist = set(lettercount)
charcount = len(list(c for c in lettercount.elements() if c != '\n'))
wordcount = lettercount[' '] + lettercount['.'] + lettercount['\n']
</code></pre>

python list python-3.x append increment