Re: strange for loop construct



* Gabriel Genellina wrote (on 1/5/2007 12:49 PM):
At Friday 5/1/2007 17:39, Sardaukary@xxxxxxxxx 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
.



Relevant Pages

  • Re: strange for loop construct
    ... Mark Elston ha escrito: ... "Whats New" section of the docs. ... List comprehensions are described ... pretty well in the "What's new in Python 2.0?" ...
    (comp.lang.python)
  • Re: PEP 289: Generator Expressions (please comment)
    ... And therefore, since you ain't gonna take list comprehensions away, ... you should be in favour, not against, generator expressions. ... I've had substantial feedback from articles on Python I had written, ...
    (comp.lang.python)
  • Re: for x in... x remains global
    ... It's an somewhat unfortunate fact that loop variables leak to the outer ... scope. ... List comprehensions also "leak" their loop variable into the surrounding ... This will also change in Python 3.0, ...
    (comp.lang.python)
  • Re: Need help porting Perl function
    ... know how to do in Python. ... ret = ... It's nothing to do with list comprehensions, ... which you are iterating. ...
    (comp.lang.python)
  • Re: Some "pythonic" suggestions for Python
    ... Get rid of lambda, get rid of def, only use = for assignments. ... WHOLE lot more syntax to support it, and that's about a thousand minuses. ... But you can still do this with Python: ... List comprehensions are ...
    (comp.lang.python)