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.
05 Answers
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'] 3 This works:
>>> L = [['some'], ['lists'], ['here']]
>>> print("\n".join([str(x) for x in L]))
['some']
['lists']
['here']
>>> 0 work for me:
L = [['some'], ['lists'], ['here']]
print("\n".join('%s'%item for item in L))this one also work:
L = [['some'], ['lists'], ['here']]
print("\n".join(str(item) for item in L))this one also:
L = [['some'], ['lists'], ['here']]
print("\n".join([str(item) for item in L])) If anyone looking for help in dict printing then here u go:
dictionary = {'test1':'value1', 'test1':'value1'}
print ('\n'.join(' : '.join(b for b in a) for a in dictionary.items())) 1 Came late, but you can simply do
print("The lists are:", [list for list in L])