Skip to content Skip to sidebar Skip to footer

Printing A List Without Line Breaks (but With Spaces) In Python

I'm trying to print the values of a list without line breaks using sys.stdout.write(). It works great, but the only problem is that I want to space each value from another. In othe

Solution 1:

Try

sys.stdout.write(" ".join(list))

The above will only work if list contains strings. To make it work for any list:

sys.stdout.write(" ".join(str(x) for x in list))

Here we use a generator expression to convert each item in the list to a string.

If your list is large and you'd like to avoid allocating the whole string for it, the following approach will also work:

for item in list[:-1]:
    sys.stdout.write(str(item))
    sys.stdout.write(" ")
if len(list) > 0:
    sys.stdout.write(list[-1])

And as mentioned in the other answer, don't call your variable list. You're actually shadowing the built-in type with the same name.


Solution 2:

You can do:

sys.stdout.write(" ".join(my_list))

Also, it's better not to name your variable list as Python already has a built-in type called list. Hence, that's why I've renamed your variable to my_list.


Solution 3:

In Python3, I tried the above solution, but I got a weird output:

for example: my_list = [1,2,3]

sys.stdout.write(" ".join(str(x) for x in ss))

the output is:

1 2 35 It will add a number at the end (5).

The best solution, in this case, is to use the print function as follows:

print(" ".join(str(x) for x in ss), file=sys.stdout)

the output: 1 2 3


Post a Comment for "Printing A List Without Line Breaks (but With Spaces) In Python"