Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Saving a for loop output into a variable

For example given the following for loop:

for i in range(3):
    print(i, '->',i+1)

Gives the output:

0 -> 1
1 -> 2
2 -> 3

How could I save this output in string form such that it is saved in a variable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So for example could say print(my_variable) and the output is as the above output.

>Solution :

A list comprehension can be used to generate the individual strings.

[f"{i} -> {i + 1}" for i in range(3)]

We can then join those with newlines.

"\n".join([f"{i} -> {i + 1}" for i in range(3)])

But we don’t need to use a list comprehension here. A generator expression will be more efficient as it doesn’t generate an entire list first and then iterate over that list.

"\n".join(f"{i} -> {i + 1}" for i in range(3))

If every line need to end in a newline, you can factor that into the f-string and then join them with an empty string.

''.join(f"{i} -> {i + 1}\n" for i in range(3))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading