# Counting words: performance of loop vs. list comprehensions [duplicate]

I am no computer scientist, so I can be naively missing some commonly implemented optimization strategies but...

Looking at two ways of counting words in a text (shown below), I tend to think that the iterative method, as it runs through each word in the text only once, will use less memory than the second method, expressed as a list comprehension.

The iterative method:

wc = {}
for w in text.split(' '):
wc[word] += 1


The list comprehension method:

wc = [text.split(' ').count(w) for w in set(text.split(' '))]


I tend to think that the list comprehension will use N^2 memory because it goes through all the words in the text for each word in the text.

Is this reasoning correct? In practice, interpreters and compilers optimize for this kind of situation?

• Tom, this is an attempt to rephrase that question as to make it more clear. – blue-dino Jul 5 '15 at 17:36
• @RodrigoStevaux Then please edit the original question. – David Richerby Jul 5 '15 at 20:23
• I did. And then @DavidRicherby told me "Rodrigo, if you want to ask a new question, ask it as a new question. Don't edit questions to completely change their meaning after they've already been answered". So I added a new question. – blue-dino Jul 6 '15 at 15:38