7

I am trying to print a list in Python that contains digits and when it prints the items in the list all print on the same line.

print ("{} ".format(ports))

here is my output

[60, 89, 200]

how can I see the result in this form:

60
89
200

I have tried print ("\n".join(ports)) but that does not work.

0

4 Answers 4

11

Loop over the list and print each item on a new line:

for port in ports:
    print(port)

or convert your integers to strings before joining:

print('\n'.join(map(str, ports)))

or tell print() to use newlines as separators and pass in the list as separate arguments with the * splat syntax:

print(*ports, sep='\n')

Demo:

>>> ports = [60, 89, 200]
>>> for port in ports:
...     print(port)
... 
60
89
200
>>> print('\n'.join(map(str, ports)))
60
89
200
>>> print(*ports, sep='\n')
60
89
200
Sign up to request clarification or add additional context in comments.

2 Comments

That's weird that in the documentation that pops up when hovering mouse over print, it doesn't mention that we need to use * when using sep.
@LoMaPh: this isn't specific to print(). It's general Python syntax to pass in multiple positional arguments as a sequence. See What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
6

i have tried print ("\n".join(ports)) but does not work.

You're very close. The only problem is that, unlike print, join doesn't automatically convert things to strings; you have to do that yourself.

For example:

print("\n".join(map(str, ports)))

… or …

print("\n".join(str(port) for port in ports))

If you don't understand either comprehensions or map, both are equivalent* to this:

ports_strs = []
for port in ports:
    ports_strs.append(str(port))
print("\n".join(ports_strs))
del ports_strs

In other words, map(str, ports) will give you the list ['60', '89', '200'].

Of course it would be silly to write that out the long way; if you're going to use an explicit for statement, you might as well just print(port) directly each time through the loop, as in jramirez's answer.


* I'm actually cheating a bit here; both give you an iterator over a sort of "lazy list" that doesn't actually exist with those values. But for now, we can just pretend it's a list. (And in Python 2.x, it was.)

Comments

4

If you are on Python 3.x:

>>> ports = [60, 89, 200]
>>> print(*ports, sep="\n")
60
89
200
>>>

Otherwise, this will work:

>>> ports = [60, 89, 200]
>>> for p in ports:
...     print p
...
60
89
200
>>>

Comments

2
ports = [60, 89, 200]

for p in ports:
    print (p)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.