Skip to content Skip to sidebar Skip to footer

Python: Printing Horizontally Rather Than Current Default Printing

I was wondering if we can print like row-wise in python. Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it wo

Solution 1:

In Python2:

data = [3, 4]
for x in data:
    print x,    # notice the comma at the end of the line

or in Python3:

for x in data:
    print(x, end=' ')

prints

3 4

Solution 2:

Just add a , at the end of the item(s) you're printing.

print(x,)
# 3 4

Or in Python 2:

print x,
# 3 4

Solution 3:

You don't need to use a for loop to do that!

mylist = list('abcdefg')
print(*mylist, sep=' ') 
# Output: # a b c d e f g

Here I'm using the unpack operator for iterators: *. At the background the print function is beeing called like this: print('a', 'b', 'c', 'd', 'e', 'f', 'g', sep=' ').

Also if you change the value in sep parameter you can customize the way you want to print, for exemple:

print(*mylist, sep='\n') 
# Output: # a# b# c# d# e# f# g

Solution 4:

If you add comma at the end it should work for you.

>>>deftest():...print1,...print2,...>>>test()
1 2

Solution 5:

my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd']
for i in xrange(0, len(my_list), 4):
    print'\t'.join(my_list[i:i+4])

Post a Comment for "Python: Printing Horizontally Rather Than Current Default Printing"