'Saving the separation of a list of lists into a variable [duplicate]

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1