37

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
kyle k
  • 5,134
  • 10
  • 31
  • 45

14 Answers14

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

Python one liner to print the range

voidpro
  • 1,652
  • 13
  • 27
  • 7
    Great answer. What's actually the meaning of the `*`? – majom Aug 30 '17 at 15:26
  • 7
    @majom `*` unpacks the sequence. – voidpro Aug 31 '17 at 06:36
  • Thanks. That I understood. Are you aware of a link to the documentation of `*`? It is hard to google for that. – majom Aug 31 '17 at 07:21
  • 4
    There are a few threads on the usage of `*`. You can very well refer [here](https://stackoverflow.com/questions/6967632/unpacking-extended-unpacking-and-nested-extended-unpacking) – voidpro Aug 31 '17 at 10:25
43

Python 2

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

Python 3

for x in range(1,11):
    print(x, end=" ") 
voidpro
  • 1,652
  • 13
  • 27
blakev
  • 4,154
  • 2
  • 32
  • 52
  • That is a very simple solution! But what are the differences between this and the more complex solutions that others gave? answer accepted! – kyle k Aug 25 '13 at 01:58
  • 1
    So, "print x," is just the short hand way of escaping the newline when you're doing a series of prints. Your print was in a for loop, so this made sense. Below, the string.join method takes an iterable and combines each element with the supplied string and returns a single string. So instead of multiple prints without newlines, you're doing one print with a newline; just pre compiling all your printable elements into one string. – blakev Aug 25 '13 at 02:03
11
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

Anubhav
  • 1,984
  • 22
  • 17
9

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 
ersran9
  • 968
  • 1
  • 8
  • 13
3

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 = ' ')
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
1

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
>>>
subhash kumar singh
  • 2,716
  • 8
  • 31
  • 43
  • so much complexity for such a simple question. Plus, neither of those escape a new line, your first is piping to stdout which needs to be imported from sys and your second is concatenating strings with a lambda and an overwritten reserved function. Why wouldn't you use ' '.join()?? Both of these are bad practice. – blakev Aug 25 '13 at 03:20
  • @BlakeVandeMerwe I am trying to cover the possible ways. – subhash kumar singh Aug 25 '13 at 06:41
1
[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

Akash Kumar Seth
  • 1,651
  • 1
  • 18
  • 22
0
for i in range(1,11):
    print(i)

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

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
bre
  • 11
  • 1
    No, it doesn't! Both the Python 3 print function and the Python 2 print statement implicitly adds a newline by default. – jmd_dk Jan 11 '17 at 21:23
0

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="")
0

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

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

Mykel
  • 1,355
  • 15
  • 25
0
n = int(input())
for i in range(1,n+1):
    print(i,end='')
  • 1
    Why is this better than the accepted answer, or different from the answer that suggest exactly this? – RalfFriedl Jun 22 '19 at 08:22
  • 1
    Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep Jun 22 '19 at 09:10
0

Use end = " ", inside the print function

Code:

for x in range(1,11):
       print(x,end = " ")
Cpt Kitkat
  • 1,392
  • 4
  • 31
  • 50
boss_man
  • 1
  • 1
0

For Python 3:

for i in range(1,10): 
    print(i,end='')
Mohit Mehlawat
  • 344
  • 3
  • 6
-1

Here's a solution that can handle x with single or multiple rows like scipy pdf:

from scipy.stats import multivariate_normal as mvn

# covariance matrix
sigma = np.array([[2.3, 0, 0, 0],
           [0, 1.5, 0, 0],
           [0, 0, 1.7, 0],
           [0, 0,   0, 2]
          ])
# mean vector
mu = np.array([2,3,8,10])

# input
x1 = np.array([2.1, 3.5, 8., 9.5])
x2 = np.array([[2.1, 3.5, 8., 9.5],[2.2, 3.6, 8.1, 9.6]])


def multivariate_normal_pdf(x, mu, cov):
    x_m = x - mu

    if x.ndim > 1:
        sum_ax = 1
        t_ax = [0] 
        t_ax.extend(list(range(x_m.ndim)[:0:-1])) # transpose dims > 0
    else:
        sum_ax = 0
        t_ax = range(x_m.ndim)[::-1]


    x_m_t = np.transpose(x_m, axes=t_ax) 
    A = 1 / ( ((2* np.pi)**(len(mu)/2)) * (np.linalg.det(cov)**(1/2)) )
    B = (-1/2) * np.sum(x_m_t.dot(np.linalg.inv(cov)) * x_m,axis=sum_ax)
    return A * np.exp(B)

print(mvn.pdf(x1, mu, sigma))
print(multivariate_normal_pdf(x1, mu, sigma))

print(mvn.pdf(x2, mu, sigma))
print(multivariate_normal_pdf(x2, mu, sigma))
luca992
  • 1,548
  • 22
  • 27