gliemezis
gliemezis

Reputation: 828

Use one line of code to print a for loop

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!

Upvotes: 10

Views: 31357

Answers (3)

Zohaib
Zohaib

Reputation: 1

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

Upvotes: -1

leongold
leongold

Reputation: 1044

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]

Upvotes: 12

zondo
zondo

Reputation: 20336

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

Upvotes: 4

Related Questions