[python] Print range of numbers on same line

Using python I want to print a range of numbers on the same line. how can I do this using python, I can do it using C by not adding \n, but how can I do it using python.

for x in xrange(1,10):
    print x

I am trying to get this result.

1 2 3 4 5 6 7 8 9 10

This question is related to python python-2.7

The answer is


n = int(input())
for i in range(1,n+1):
    print(i,end='')

Use end = " ", inside the print function

Code:

for x in range(1,11):
       print(x,end = " ")

Another single-line Python 3 option but with explicit separator:

print(*range(1,11), sep=' ')


for i in range(1,11):
    print(i)

i know this is an old question but i think this works now


str.join would be appropriate in this case

>>> print ' '.join(str(x) for x in xrange(1,11))
1 2 3 4 5 6 7 8 9 10 

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code

        for i in range(1,n):
            print(i,end="")

[print(i, end = ' ') for i in range(10)]
0 1 2 3 4 5 6 7 8 9

This is a list comprehension method of answer same as @Anubhav


>>>print(*range(1,11)) 
1 2 3 4 5 6 7 8 9 10

Python one liner to print the range


This is an old question, xrange is not supported in Python3.

You can try -

print(*range(1,11)) 

OR

for i in range(10):
    print(i, end = ' ')

for i in range(10):
    print(i, end = ' ')

You can provide any delimiter to the end field (space, comma etc.)

This is for Python 3