Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 print(array) 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 are right) in a single line, and without the brackets and commas?

like image 676
KimioN42 Avatar asked Jun 04 '16 00:06

KimioN42


People also ask

How do I print a list of values in one line in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do I make a list in one line in Python?

To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.

How do I print an integer in one line in Python?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.


1 Answers

Yes that is possible in Python 3, just use * before the variable like:

print(*list) 

This will print the list separated by spaces.

(where * is the unpacking operator that turns a list into positional arguments, print(*[1,2,3]) is the same as print(1,2,3), see also What does the star operator mean, in a function call?)

like image 96
Nikhil Gupta Avatar answered Sep 19 '22 20:09

Nikhil Gupta