I have found an example online of how to count items in a list with the sum()
function in Python; however, when I search for how to use the sum()
function on the internet, all I can find is the basic sum(iterable, start)
, which adds numbers together from each element of the list/array.
Code I found, where each line of the file contains one word, and file = open("words.txt", "r")
:
wordsInFile = sum(1 for line in file)
this works in my program, and I kind of see what is happening, but I would like to learn more about this kind of syntax, and what it can or can't recognize besides line. It seems pretty efficient, but I can't find any website explaining how it works, which prevents me from using this in the future in other contexts.