SomeOne SomeOne - 1 year ago 83
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('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:

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

Answer Source

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.


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

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.


>>> print('The lists are:', '\n'.join([str(lst) for lst in L]))
The lists are: ['some']
>>> print('The lists are:', '\n'.join([str(lst) for lst in L]), sep='\n')
The lists are:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download