1

A similar question with Print new output on same line, which does not answer my question.

I wonder how (with python 2 and 3) to print all to one line. e.g., By running:

print("Result of:\t")

mylist1=[]
mylist2=[]
name = "class_1"

for i in range(-5, 0):
    mylist1.append(i)
for j in range(1, 6):
    mylist2.append(j)
print(name+"\t")
print(mylist1+"\t"+mylist2)

What I got:

Result of:  
class_1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-1e34909da6d3> in <module>
     10     mylist2.append(j)
     11 print(name+"\t")
---> 12 print(mylist1+"\t"+mylist2)
     13 

TypeError: can only concatenate list (not "str") to list

However, what I want is to print them in one line separated with "\t":

Result of:    class_1    [-5, -4, -3, -2, -1]    [1, 2, 3, 4, 5]

which solution is usually used for this case?

Emily
  • 83
  • 9

4 Answers4

3
  • You can use sep argument to different values without using +.
  • You also need to cast list to str to print with []
mylist1=[]
mylist2=[]
name = "class_1"

for i in range(-5, 0):
    mylist1.append(i)
for j in range(1, 6):
    mylist2.append(j)
print("Result of:", name, str(mylist1), str(mylist2), sep='\t')
Poojan
  • 3,366
  • 2
  • 17
  • 33
  • Or in current versions of Python with an f-string: `print(f'Result of:\t{name}\t{mylist1}\t{mylist2}')` – Matthias Apr 21 '20 at 19:42
1
mylist1=[]
mylist2=[]
name = "class_1"

for i in range(-5, 0):
    mylist1.append(i)
for j in range(1, 6):
    mylist2.append(j)
print("Result of:", name, str(mylist1), str(mylist2), sep='\t')
Harshit Ruwali
  • 1,040
  • 2
  • 10
  • 22
1

For python 3.x

print(name, sep="\t")


For python 2.x (in python 2.x print is not a function rather it is keyword)

Still achieve the same in python 2.x

from __future__ import print_function
print_function(name, sep="\t")

or

print "\t".join(list[name])

Edited (added examples):

for python 3.x

print("Result of:", name, str(mylist1), str(mylist2), sep='\t')

for python 2.x

 print "\t".join([name, str(mylist1), str(mylist2)])
Shivam Seth
  • 677
  • 1
  • 8
  • 21
0
print(list1,"\t",list2)

This gives the desired output

lil_noob
  • 87
  • 1
  • 12