Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ending with a for loop in python

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.

like image 727
eitanlees Avatar asked Mar 12 '14 22:03

eitanlees


People also ask

How do you end a for loop?

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 .

How do you start and end a for loop in Python?

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.

How do you end a for loop in a while loop in Python?

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.

DO for loops need an end in Python?

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.


Video Answer


4 Answers

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).

like image 118
TessellatingHeckler Avatar answered Sep 23 '22 19:09

TessellatingHeckler


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.

like image 36
morningstar Avatar answered Sep 19 '22 19:09

morningstar


First of all:

  1. this is considered bad style—you're essentially just abusing the list comprehension syntax to get what's effectively a different notation for imperative for loops.
  2. this only works in Python 3 where print is a function by default, or when you do from __future__ import print_function in Python 2.x

However, 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.

like image 31
Erik Kaplun Avatar answered Sep 23 '22 19:09

Erik Kaplun


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

like image 43
Adam Smith Avatar answered Sep 21 '22 19:09

Adam Smith