0
import string

CHARACTERS = list(string.ascii_letters) + [" "]

def letter_frequency(sentence):
    frequencies = [(c, 0) for c in CHARACTERS]
    for letter in sentence:
        index = CHARACTERS.index(letter)
        frequencies[index] = (letter, frequencies[index][1] + 1)
    for item in frequencies:
        if item[1] == 0:
            frequencies.remove(item)
    return frequencies

This is based on an exercise in the book Object Oriented Programming. It's just a means of counting letters in a sentence and presenting them as a list of tuples with letters and their corresponding counts. I wanted to remove the letters in the resulting list of the alphabet that have '0' count, but when I execute the code, it only removes every 2nd item in the list. What am I doing wrong?

Matthias
  • 12,873
  • 6
  • 42
  • 48

1 Answers1

0

There is another short way to calculate the number of times a letter occurred inside a sentence:

from collections import Counter
counter = Counter('Put your sentence here')
print(counter)
NeverQuit
  • 45
  • 7