Vladimir Putin
Vladimir Putin

Reputation: 701

How can I fit a short loop on to one line?

Let's say I have a short loop like this:

for i in range(10):
    print "Hello"

How, if possible, can I fit this onto one line?

Upvotes: 0

Views: 271

Answers (3)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44112

Alternative - use map

(You tagged it as Python 2.7, so we do not have print as function initially)

Assuming you want to apply a function on each element in the list, map will loop over.

>>> from __future__ import print_function
>>> lst = ["a", "b", "c"]

Now I have print defined as a function and have the list to loop over:

>>> map(print, lst)
a
b
c
[None, None, None]

The [None, None, None] is list of results, which isNone` in case of print. Returning a list costs some time. Depending of further use of the results it can be small advantage or disadvantage.

Note, that in Python 3 the map behaves a bit differently, it returns special sort of result of type map which has to be forced to iterate, e.g. by placing into list call. But this is not in scope of your question.

Upvotes: 1

arshajii
arshajii

Reputation: 129507

How, if possible, can I fit this onto one line?

You can just place it on a single line:

for i in range(10): print "Hello"

But that doesn't do you much, and goes against convention. You shouldn't try to cram many things onto one line when there's no reason to (readability counts!).

As an aside, generally _ is used as the loop control variable when it's never needed in the loop's body:

for _ in range(10):
    print "Hello"

Upvotes: 4

merlin2011
merlin2011

Reputation: 75565

Just put the statement right after the :.

for i in range(10):  print "Hello"

Upvotes: 1

Related Questions