-1

Hi

I am trying to shorten my code with some for loops inside of print functions, but I run into this problem:

List = ["######################",
        "#                    #",
        "#                    #",
        "#     Hello There    #",
        "#                    #",
        "#                    #",
        "######################"]

print(l for l in List)

Output:

<generator object <genexpr> at 0x000001F704B0B820>

is there a way to make this work without doing:

for l in List:
    print(l)

Output:

######################
#                    #
#                    #
#     Hello There    #
#                    #
#                    #
######################

or do I have to stick with that?

I am sorry if this question is somewhere else, I just couldn't find it. If you manage to find it, feel free to send a link instead of explaining it here too.

thanks in advance

KrissKloss
  • 61
  • 3
  • You cannot use a loop *inside* a `print`... – ShlomiF Jun 30 '21 at 06:50
  • 1
    Does this answer your question? [Printing list elements on separated lines in Python](https://stackoverflow.com/questions/6167731/printing-list-elements-on-separated-lines-in-python) – buran Jun 30 '21 at 06:57
  • Does this answer your question? [Python: print a generator expression?](https://stackoverflow.com/questions/5164642/python-print-a-generator-expression) – Jonath Sujan Jun 30 '21 at 07:18

3 Answers3

3

You cannot use loop inside print() but you can do

spam = ["######################",
        "#                    #",
        "#                    #",
        "#     Hello There    #",
        "#                    #",
        "#                    #",
        "######################"]
print('\n'.join(spam))
buran
  • 13,682
  • 10
  • 36
  • 61
1

The <generator> message means your expression gets turned into a generator. You can turn a generator into a list, for example:

print(list(l for l in List))

... or more generally by performing an operation which evaluates the generator until exhaustion and returns the result of the iteration.

Unfortunately, the output from the above is the output of print(list(...) without any formatting:

['######################', '#                    #', '#                    #', '#     Hello There    #', '#                    #', '#                    #', '######################']

Fortunately, you can implicitly perform the evaluation by passing the generator to join:

print("\n".join(l for l in List))

... which of course is more simply expressed as

print("\n".join(List))
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

You can use the join method:

print("\n".join(List))

This is the easiest way you can do, join(...) takes an interable as a parameter so that you can pass a list, tuple, or a set. And then join all together using the delimiter that is \n.

allexiusw
  • 1,533
  • 2
  • 16
  • 23