gurkha_dawg gurkha_dawg - 2 months ago 4x
Python Question

I need help in understanding the function of the number "1" and the word 'sum' in the code below

This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.

x = raw_input('Enter the word')

print ("Capital Letters: ", sum(1 for d in x if d.isupper()))
print ("Small letters:" , sum(1 for d in x if d.islower()))

Could anyone help me explain why 1 is used ? also why is sum used instead of len?


He's filtering all the capital letters in a string and building a list of 1's for each item in the remaining list. Then he's summing that list. Since the list comprehension is building a generator and not a list, len cannot be used.

(Edited. Previous version said len could be used equivalently)