1

I have a list containing a variable number of items,
list_example = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...]

and I'd like to format it into a string as follows:
0 1 2 3 4 5 6 7 8 9 ...

Currently, I'm doing this using a simple for loop:

string = ""

for i in range(len(list_example) - 1):
    string += str(list_example[i]) + "  "
string += str(list_example[-1])  

It works well, but I feel like it must be a better (more compact) way of achieving that. If anybody knows how to do it, please, let me know!

Hiago Prata
  • 97
  • 11

1 Answers1

2

You can use join:

print(" ".join(map(str,list_example)))
Julien
  • 13,986
  • 5
  • 29
  • 53
  • If you don't need the resulting string, just need to `print` the values space separated, you can just do `print(*list_example)` directly. You'd only bother `map`-ing with `str` and `join`ing if you needed the final string form as a single string. – ShadowRanger May 08 '18 at 02:29