Use one line of code to print a for loop

Question:

I have a list of strings stored in results that I want to print one at a time to look like this:

String 1
String 2
String 3
etc.

Right now, I have this, which works fine:

for line in results:
    print line

I am just trying to see if it is possible to condense it into a single line to determine the simplest, shortest solution.

I am able to assign a variable to a list, for example numbers = [i for i in range(5)].
Is it then possible to convert my code to something like this?

print line for line in results

I have tried a couple variations to no avail, and I have exhausted my research on the topic and haven’t found anything conclusive. I’m just curious to see what is possible. Thanks!

Asked By: gliemezis

||

Answers:

print('n'.join(str(line) for line in results))

Answered By: zondo
for line in results: print line

Using Python 3.0 print function with list comprehension:

from __future__ import print_function

[print(line) for line in results]
Answered By: leongold

Best solution for printing in single line will be using

end = " "

Here is my code:

arr = [1, 2, 3, 4, 5]
for i in range(0, len(arr)):
   print(arr[i])

If I use the above code the answer

1
2
3
4
5

By using the solution below:

arr = [1, 2, 3, 4, 5]
for i in range(0, len(arr)):
   print(arr[i], end = " ")

We get the answer:
1 2 3 4 5

Answered By: Zohaib
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.