0

Given the following list:

[['ORGANIZATION', 'EDUCATION', 'UniversityWon', 'FormMathematics'], ['PERSON', 'Sixth', 'Economics'], ['GPE', 'FrenchUK', 'London']]

I have the following for loop that prints them in the desired way:

for i in output:
    print(i[0], '->', ', '.join(i[1:]))

Output of:

ORGANIZATION -> EDUCATION, UniversityWon, FormMathematics
PERSON -> Sixth, Economics
GPE -> FrenchUK, London

How can I save this output into a variable such that if I executed print(variable), the above-mentioned output would be printed?

TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
daniel stafford
  • 241
  • 1
  • 8

1 Answers1

0

You just need to assign it to a variable, but make sure you have initialized the variable outside of the for loop first:

variable = ""
for i in output:
    variable += i[0] + '->' + ', '.join(i[1:]) + "\n"
print(variable.strip()) # strip() is used to remove the last "\n"

Second approach

It seems the more efficient approach (Thanks to @ThierryLathuille for the comment) would be using list of line and joining them using join function:

variable = "\n".join([x[0] + '->' + ', '.join(x[1:]) for x in output])
print(variable)

Output of both above-mentioned answers would be the same:

ORGANIZATION->EDUCATION, UniversityWon, FormMathematics
PERSON->Sixth, Economics
GPE->FrenchUK, London
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
  • 1
    Repetitively appending to a string is inefficient in Python. The efficient, traditional way to do this would be to append each line to a list, and finally to `join` it with `\n`. – Thierry Lathuille Mar 11 '22 at 08:25
  • @ThierryLathuille Wouldn't it be still inefficient if we used for loop to append the line to a list? I ask this out of curiosity because both are using `for` loops and I can't distinguish between these two. – TheFaultInOurStars Mar 11 '22 at 08:29
  • 1
    @AmirhosseinKiani as strings are immutable, every time you append something to a string a new string is created on contrary to a list which gets appended. And repeated appending to a string is NOT recommended for performance reasons in Python. – balu Mar 11 '22 at 08:33
  • 1
    You can find more details, timings etc in https://stackoverflow.com/questions/4166665/python-join-or-string-concatenation , https://stackoverflow.com/questions/3055477/how-slow-is-pythons-string-concatenation-vs-str-join for example. – Thierry Lathuille Mar 11 '22 at 08:35
  • The second approach doesn't save the output to a variable though. – daniel stafford Mar 11 '22 at 09:37
  • @danielstafford I have edited the second approach too, in order to fit to your question – TheFaultInOurStars Mar 11 '22 at 09:40