I am experiencing a bit of confusion with how to place a for loop at the end of a line in python, for instance
for i in x:
print i
produces the expected result but if I run
print i for i in x
I get a syntax error. Could someone explain a little more about how one goes about putting your for loops at the end of a line like this.
The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .
Unlike other languages, Python does not use an end statement for its loop syntax. The initial Loop statement is followed by a colon : symbol. Then the next line will be indented by 4 spaces.
The most Pythonic way to end a while loop is to use the while condition that follows immediately after the keyword while and before the colon such as while <condition>: <body> . If the condition evaluates to False , the program proceeds with the next statement after the loop construct. This immediately ends the loop.
The code block in a for loop (in python) has no curly braces nor an "end" keyword indicating the point where the block terminates. All other languages have the code block wrapped in some way to move execution back to the top for each item.
In earlier versions of Python, the idea of list comprehensions was introduced to neaten up these two patterns of code:
# Go through each item in a list and run a test on them
# build a new list containing only items that pass the test
results = []
for item in somelist:
if sometest(item):
results.add(item)
and
# build a new list by changing every item in a list in the
# same way
results = []
for item in somelist:
results.add(2 * item)
by adding a new syntax that includes doing all three things in one - changing the items and/or testing them to only include some in the result, and creating the list of the results:
results = [2 * item for item in somelist if sometest(item)]
# results is a list
This feature uses the [] syntax that indicates "list" in Python, and it builds a list right away in memory.
Sometimes you don't want or need the entire list built in memory right away, so later versions of Python introduced generator expressions - the same idea, but they save memory by quickly returning a generator which you can iterate over as if it was a list, and it builds the list as and when you use it.
But they can't have the same syntax and be a direct swap out because they behave slightly differently, so they use () instead of [], e.g.:
somelist = [1,2,3,4,5]
results = (2 * item for item in somelist if sometest(item))
# results is a generator
If you try and call a function with this, you get two layers of parentheses:
function((2 * item for item in somelist))
Which looks silly, so you can leave one out:
function(2 * item for item in somelist)
Which appears to be a standalone backwards for
loop on its own, but it actually isn't.
So with parentheses you can write this:
>>> print (item for item in [1,2,3])
<generator object <genexpr> at 0x7fe31b8663c0>
Which is the closest thing to what you wrote that is valid syntax in Python 2.x, but it doesn't do what you expect, and ^^ is what it does and why.
Or this:
>>> print [item for item in [1,2,3]]
[1,2,3]
Which generates a list and prints the list, the other close thing to what you wrote, but still not what you expected.
-- (there really isn't much point in me posting now a bunch other answers have appeared while I was writing this, but eh).
expression for i in x
doesn't mean anything by itself in Python. You can have
(expression for i in x)
[expression for i in x]
But you can't do
[print i for i in x]
because print isn't an expression, it's a statement.
First of all:
print
is a function by default, or when you do from __future__ import print_function
in Python 2.xHowever, if you insist on putting the for ...
part after the print i
part, you can do:
[print(i) for i in x]
(but I'm writing that example for purely "academic" purposes)
P.S. if you let us know what you want to do, we might be able to provide a suitable overall solution, but if you're just asking for the sake of it, then that's it.
You can't. You've probably seen a generator expression, which takes the form x for x in iter
. a for
loop is slightly different, though you can definitely see for x in iter
inside the genexp.
In Python3, you can do:
print(*(i for i in x))
And as @wim points out in the comments, you can make it more "for
loopy" by doing
print(*(i for i in x), sep='\n')
You can of course do arbitrary changes since this is a genexp, so e.g. i**2 for i in x
will give you the square of each item in x
, i for i in x if i%2
will give all odd numbers in x
, etc.
This will create a generator of each item in x
, then pass each one in turn (using the *
assignment the same way *args
is built and etc) as separate arguments to print
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With