user2315898
user2315898

Reputation:

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 other words, instead of 123, I want 1 2 3. I looked on the website for a solution, but I haven't found something that involves lists.

When I add " " to sys.stdout.write(list[i]), like this: sys.stdout.write(list[i], " "), it doesn't print at all. Any suggestions how to fix that?

Here's my code:

import random
import sys

list = []

length = input("Please enter the number of elements to be sorted: ") 
randomNums = input("Please enter the number of random integers to be created: ") 
showList = raw_input("Would you like to see the unsorted and sorted list? y/n: ")

for i in range(length):
    list.append(random.randint(1,randomNums))

if(showList == "y"):
    for i in range(length):
       sys.stdout.write(list[i], " ")

Upvotes: 4

Views: 10877

Answers (3)

TSobhy
TSobhy

Reputation: 99

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

Upvotes: 0

Alexei Sholik
Alexei Sholik

Reputation: 7469

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.

Upvotes: 9

Simeon Visser
Simeon Visser

Reputation: 122376

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.

Upvotes: 3

Related Questions