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 on a new line) using the function print():

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

I know this is not true, but I hope you understand this idea. Could you tell me if this is possible? If so, how?

I know I can do this:

for list in L:
    print(list)

However, I would like to know if there are other options.

+4
source share
4 answers

Apply the whole object Las a separate argument:

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

By setting septo a new line, this will print all the objects in the list in new lines.

Demo:

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

, :

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

'The lists are:', sep='\n' .

:

>>> 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']
+14

:

>>> L = [['some'], ['lists'], ['here']]
>>> print("\n".join([str(x) for x in L]))
['some']
['lists']
['here']
>>>
+3

work for me:

L = [['some'], ['lists'], ['here']]
print("\n".join('%s'%item for item in L))

this one also works:

L = [['some'], ['lists'], ['here']]
print("\n".join(str(item) for item in L))

it's the same:

L = [['some'], ['lists'], ['here']]
print("\n".join([str(item) for item in L]))
+1
source

If someone is looking for help in dictation, then go:

dictionary = {'test1':'value1', 'test1':'value1'}


print ('\n'.join(' : '.join(b for b in a) for a in dictionary.items()))
0
source

All Articles