How to properly print a list?
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print
is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map()
function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join()
. Then, the %
string formatting operator substitutes the string in instead of %s
in "[%s]"
.
In Python, is there an elegant way to print a list in a custom format without explicit looping?
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.
How to print a list in Python nicely
from pprint import pprint
pprint(the_list)
(Python) Unable to properly print out a list into a string
The problem is that your function prints a value, rather than returning one (which means it returns the default value of None
)… but then, within that same function, you try to call it and use its return value. Which is, of course, None
.
Calling str()
on None
doesn't help; it just gives you the string "None"
.
If you're trying to "get back" the values that you printed to the screen and then forgot about, there's no way to do that. If you want those values, don't forget about them in the first place!
What you probably want is something like this:
def strlist(lst):
if not lst:
return " "
else:
return str(lst[0]) + " " + strlist(lst[1:])
def printlist(lst):
print strlist(lst)
… which has a function that returns something and uses returned values instead of just printing, or this:
def printlist(lst):
if not lst:
print " "
else:
print str(lst[0]) + " "
printlist(lst[1:])
… which has a function that doesn't try to use the return value it will never get.
(I've fixed two other minor things along the way—don't name a variable list
, because that's the name of the type and you don't want to hide it, and don't check == ""
when an empty list is already false.)
Of course it's worth noting that strlist
in that case is just a slow and complicated version of " ".join
, so you could just do:
def printlist(lst):
print " ".join(map(str, lst))
Also, either way, I'm not sure where you do and don't want newlines. You add spaces at the end of lines, so presumably you want other stuff to follow on the same line (otherwise why bother with the space), but then you do print
statements without the magic comma, which always adds a newline after each such print
.
print list elements line by line - is it possible using format
You can use the string formatter on really any kind of string, including multi-line string. So of course, if you had a format string '{}\n{}\n{}'
you could pass three items to it, and they would be all placed on separate lines.
So with a dynamic number of elements you want to print, all you need to do is make sure that the format string contains the same number of format items too. One way to solve this would be to construct the format string dynamically. For example this:
'\n'.join('{}' for _ in range(len(my_list))).format(*my_list)
So you essentially create a format string first, by having a generator produce one format item {}
per element in my_list
, and joining these using a newline character. So the resulting string looks something like this: {}\n{}\n…\n{}\n{}
.
And then you use that string as the format string, and call format
on it, passing the unpacked list as arguments to it. So you are correctly filling all spots of the format string.
So, you can do it. However, this is not really a practical idea. It looks rather confusing and does not convey your intention well. A better way would be to handle each item of your list separately and format it separately, and only then join them together:
'\n'.join('{}'.format(item) for item in my_list)
As for just printing elements line by line, of course, the more obvious way, that wouldn’t require you to build one long string with line breaks, would be to loop over the items and just print them one-by-one:
for item in my_list:
print(item)
# or use string formatting for the item here
print('{}'.format(item))
And of course, as thefourtheye suggested, if each loop iteration is very simple, you can also pass the whole list to the print function, and set sep='\n'
to print the elements on separate lines each.
Printing Lists as Tabular Data
Some ad-hoc code:
row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
print(row_format.format(team, *row))
This relies on str.format()
and the Format Specification Mini-Language.
How to properly print the content of a list in C#
You're printing cars
- the collection - instead of car
- the current iteration.
Change it to Console.WriteLine(car);
.
How to print the list in 'for' loop using .format() in Python?
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
print("{}.{}".format(i + 1, names[i]))
Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue.
This is an example where the error message is very useful in diagnosing the problem.
Related Topics
How to Get Item's Position in a List
Override a Method at Instance Level
Speed of Calculating Powers (In Python)
How Does a Python for Loop with Iterable Work
Pygame Image Transparency Confusion
Python: Load Variables in a Dict into Namespace
How to Use Brew Installed Python as the Default Python
How to Do Assignments in a List Comprehension
Catching an Exception While Using a Python 'With' Statement
How to Add a Calculated Field to a Django Model
Why Sum on Lists Is (Sometimes) Faster Than Itertools.Chain
Strange Behavior of Lists in Python
How to Dump a Dict to a JSON File
Python Filter List of Dictionaries Based on Key Value
How to Set the Figure Title and Axes Labels Font Size in Matplotlib
How to Convert List of Key-Value Tuples into Dictionary
Opencv Error: (-215)Size.Width>0 && Size.Height>0 in Function Imshow