python in-line for loops

Adam

I'm wondering if there is a way in python to use a simplified, in-line for loop to do different things. For example:

for x in range(5):
    print(x)

to be written in a simpler form, such as

print (x) for x in range(5)

but this does not seem to be working.

I've been googling for finding the right syntax for a couple hours without success. The only alternative I found is, when the in-line for loop is used to access elements of a list:

print ([x for x in range(5)])

is working, but it is doing something else, than what I'm looking for.

Can someone point to the right syntax or let me know if there are any restrictions? (maybe in-line for loops work only about lists?)

Zac

Quick answer:

There is no such a thing as "in line for loops" in python

A trick that works:

in python 3.*:

[print(x) for x in range(5)]

Because print is a function

In python 2.* printis not a function but you could define myprint and use it like this:

>>> def myprint(x):
...     print x
... 
>>> _=[ myprint(x) for x in range(5)]
0
1
2
3
4

More in depth:

What you call "in-line for loops" or "shortforms" are actually list comprehensions and (quoting documentation)

provide a concise way to create lists

The first part of a list comprehension (before the forkeyword) must contain an expression used to create list values. If your expression contains a function that has the (side) effect of printing something it works... but it is exactly a side effect. What you are really doing is creating a list and then discarding it.

Note that you can't assign values (like q += (x * y)) in a list comprehension because assignments are not expressions.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related