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!

2

2 Answers

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]
1

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

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest