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 w
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])
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).
You can apply the list as separate arguments:
print(*L)
and let print()
take care of converting each element to a string. You can, as always, control the separator by setting the sep
keyword argument:
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join()
:
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L
!
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())