SomeOne SomeOne - 1 month ago 7
Python Question

Python: for loop inside print()

I have a question about Python (3.3.2).

I have a list:

L = [['some'], ['lists'], ['here']]


I want to print these nested lists (each one on a new line) using the
print()
function:

print('The lists are:', for list in L: print(list, '\n'))


I know this is incorrect but I hope you get the idea. Could you please tell me if this is possible? If yes, how?

I know that I could do this:

for list in L:
print(list)


However, I'd like to know if there are other options as well.

Answer

Apply the whole L object as separate arguments:

print('The lists are:', *L, sep='\n')

By setting sep to a newline this'll print all list objects on new lines.

Demo:

>>> L = [['some'], ['lists'], ['here']]
>>> print('The lists are:', *L, sep='\n')
The lists are:
['some']
['lists']
['here']

If you have to use a loop, do so in a list comprehension:

print('The lists are:', '\n'.join([str(lst) for lst in L]))

This'll omit the newline after 'The lists are:', you can always use sep='\n' here as well.

Demo:

>>> print('The lists are:', '\n'.join([str(lst) for lst in L]))
The lists are: ['some']
['lists']
['here']
>>> print('The lists are:', '\n'.join([str(lst) for lst in L]), sep='\n')
The lists are:
['some']
['lists']
['here']
Comments