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?


marked as duplicate by Tom van der Zanden, Rick Decker, David Richerby, André Souza Lemos, D.W. Jul 6 '15 at 3:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ Tom, this is an attempt to rephrase that question as to make it more clear. $\endgroup$ – blue-dino Jul 5 '15 at 17:36
  • 1
    $\begingroup$ @RodrigoStevaux Then please edit the original question. $\endgroup$ – David Richerby Jul 5 '15 at 20:23
  • $\begingroup$ 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. $\endgroup$ – blue-dino Jul 6 '15 at 15:38