KimioN42 KimioN42 - 1 year ago 61
Python Question

Printing an int list in a single line python3

I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:

#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces
array = [int(s) for s in string.split()]

Apparently it works, since when I type in '1, 2, 3' and do a
the output is:

[1, 2, 3]

But I want to print it in a single line without the brackets, and with a space in between the numbers, like this:

1 2 3

I've tried doing:

for i in array:
print(array[i], end=" ")

But I get an error:

2 3 Traceback (most recent call last):

print(array[i], end=" ")

IndexError: list index out of range

How can I print the list of ints (assuming my first two lines of code is right) in a single line, and without the brackets and commas?

Answer Source

You want to say

for i in array:
    print(i, end=" ")

The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).

You can get the same effect with print(" ".join(map(str,array))).