Would be better not to iterate over the characters but to use sum
with len
and the string methods lower
and count
:
count = sum(len(currentString) for currentString in givenStrings)
numTs = sum(currentString.lower().count('t') for currentString in givenStrings)
The sum
function can take any iterable. It sums.
The first applies len
to each item in the list. Which sum
consumes to produce a total.
The second uses the lower
method to convert each of the strings to lowercase and then calls the count
method to get the number of occurrences of the string 't'
. Which sum
consumes to produce a total.
In each of the uses, the argument is a generator expression (a for b in c)
the parentheses can be omitted when it is the only argument to a function. sum(a for b in c)
is the same as sum((a for b in c))
. When it is not the only argument the parentheses are required.
There are other built-in functions that also take iterables most notably min
, max
, any
, all
. Note that min
and max
take a keyword argument key
such that max((a for a in b), key=len)
returns the item in the iterable that is the longest. The heapq.nsmallest
and heapq.nlargest
functions are effectively natural extensions of min
and max
. I'm fond of any
and all
especially when combined with not
.