# 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?