print on same line in python

How to Print in Same Line in Python

Sometimes you may need to print different items on a single line. Unlike other languages, the print function in python automatically adds a newline character after what it prints. In this article, we will look at how to print in same line in python.


How to Print in Same Line in Python

Let us say you have the following line in python.

a=[1,2,3,4,5]

Let us try printing the different list items in python

for i in a:
	print(i)
	
1
2
3
4
5

As you can see, python prints each item on a separate line.

Let us look at how to print the above items on a single line.

Python 2.x

If you are using python 2.x you can print all items on single line by adding comma after print command.

for i in a:
	print(i),

1 2 3 4 5

In the above code, we simply add a comma immediately after the print command, causing python to print all items of the loop.

Python 3.x

If you are using python 3.x, you need to modify the call to print function as shown below in bold.


for i in a:
	print(i, end =" ")

1 2 3 4 5

That’s it. In this article, we have seen a couple of ways to print multiple items on single line.

Also read:

How to Import from Another Folder in Python
How to Enable Apache MPM Prefork
How to Change Apache Prefork to Worker in Ubuntu
How to Enable PHP in Ubuntu
How to Install Rspamd in Ubuntu

Leave a Reply

Your email address will not be published.