-1

Imagine I have something like:

numberlist = [0,1,2,3,4,5]

for number in numberlist:
    print(number)

and it would print me every number, right?

But how can I print all these numbers in one line? I expect to get

0,1,2,3,4,5 or 0 1 2 3 4 5

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Grot
  • 1
  • If you just want to see the list you can `print(numberlist)` as well. – nbwoodward Aug 29 '18 at 18:41
  • If you Google the phrase *Python print list*, you’ll find tutorials that can explain it much better than we can in an answer here. – Prune Aug 29 '18 at 18:45

3 Answers3

2

You can use the keyword argument end in print. Like this:

for number in number_list:
    print(number, end=' ')

Which, for number_list = [0,1,2,3,4,5], will give you the output:

0 1 2 3 4 5

The default for end is '\n' which is why each number is printed on a separate line.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
  • if you're using python 2, you can import the print function with `from __future__ import print_function`. it's called the same way – wpercy Aug 29 '18 at 18:41
1
f = " ".join((str(i) for i in numberlist))
print (f)
GraphicalDot
  • 2,644
  • 2
  • 28
  • 43
0
print(",".join(str(i) for i in l))

or

print(" ".join(str(i) for i in l))
Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
  • correct, but you should hone your formatting – MCO Aug 29 '18 at 18:46
  • 1
    @MCO fixed the formatting for them. Rabia: nevertheless you should maybe add some explanation about *how* and *why* your code works to improve its long-term value. – Thomas Flinkow Aug 29 '18 at 19:11