Markus Hubig wrote:
Hi @all,

within diveintopython I often found a for-statement like this:

f for f in bla:
    print f

So what actually is the first f for ... is it just to declare f before
starting the for loop? I can't find any information on python.org
and it's hard to google this kinda stuff.

- Markus

Please give us a reference, as to exactly where you saw that. It gives a syntax error in Python 2.62, as I expected it would. That's not how a for statement works.


On the other hand, if you enclose that phrase in square brackets, it makes a list comprehension.

mylist = [f for f in bla]

A list comprehension builds a new list, where the first pieces says what goes into the list, and the second part describes how to generate it. In this case, if bla is already a list, this just copies the list. But consider
mylist = [f*f  for f in bla]

That builds a new list from the old, where each item is the square of the corresponding old item.

List comprehension is something you can look up in the help. Also look up generator expression, which uses similar syntax.


DaveA
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to