Adam
Adam

Reputation: 332

python in-line for loops

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

Upvotes: 1

Views: 5701

Answers (2)

Zac
Zac

Reputation: 2250

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.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

You can join your items with new line character and print it.But this is not a proper way for just printing I recommend the your first code using a simple loop.

>>> print '\n'.join([str(x) for x in range(5)]) 
0
1
2
3
4

Or since map performs better at dealing with built-in functions rather than list comprehension you can use map(str, range(5))

The result would be your first code :

>>> for x in range(5):
...     print(x)
... 
0
1
2
3
4

You can also do it in one line :

>>> for x in range(5):print(x)
... 
0
1
2
3
4

Upvotes: 1

Related Questions