strange for loop construct

Mark Elston m.elston at advantest-ard.com
Fri Jan 5 16:05:02 EST 2007


* Gabriel Genellina wrote (on 1/5/2007 12:49 PM):
> At Friday 5/1/2007 17:39, Sardaukary at gmail.com wrote:
> 
>> wordfreq = [wordlist.count(p) for p in wordlist]
>>
>> I would expect
>>
>> for p in wordlist:
>>     wordfreq.append(wordlist.count(p))
>>
>>
>> I didn't know you could have an expression in the same line.
> 
> That's known as a "list comprehension" and is roughly equivalent to your 
> code. Section 5 of the tutorial covers them. 
> http://docs.python.org/tut/node7.html
> 
> 

If you have a Python installation you should be able to find the
"Whats New" section of the docs.  List comprehensions are described
pretty well in the "What's new in Python 2.0?" section.  This gives
some simple examples as well as the rationale behind them.

Mark



More information about the Python-list mailing list