[python] Print a list of space-separated elements in Python 3

I have a list L of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don't want a space after the last element of the list (or before the first).

In Python 2, this can easily be done with the following code. The implementation of the print statement (mysteriously, I must confess) avoids to print an extra space before the newline.

L = [1, 2, 3, 4, 5]
for x in L:
    print x,
print

However, in Python 3 it seems that the (supposedly) equivalent code using the print function produces a space after the last number:

L = [1, 2, 3, 4, 5]
for x in L:
    print(x, end=" ")
print()

Of course there are easy answers to my question. I know I can use string concatenation:

L = [1, 2, 3, 4, 5]
print(" ".join(str(x) for x in L))

This is a quite good solution, but compared to the Python 2 code I find it counter-intuitive and definitely slower. Also, I know I can choose whether to print a space or not myself, like:

L = [1, 2, 3, 4, 5]
for i, x in enumerate(L):
    print(" " if i>0 else "", x, sep="", end="")
print()

but again this is worse than what I had in Python 2.

So, my question is, am I missing something in Python 3? Is the behavior I'm looking for supported by the print function?

This question is related to python python-3.x pretty-print

The answer is


Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.

The best way is to print joined string of numbers converted to strings.

print(" ".join(list(map(str,l))))

Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)

Result:

Time 74344.76 71790.83 196.99 153.99

The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.

Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).


list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to pretty-print

Print a list of space-separated elements in Python 3 Printing out a linked list using toString How can I pretty-print JSON using Go? JSON.stringify output to div in pretty print way Convert JSON String to Pretty Print JSON output using Jackson How to prettyprint a JSON file? Pretty-print a Map in Java Pretty-Print JSON Data to a File using Python How do I pretty-print existing JSON data with Java? Pretty-Printing JSON with PHP