Format all elements of a list

Question:

I want to print a list of numbers, but I want to format each member of the list before it is printed.
For example,

theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

I want the following output printed given the above list as an input:

[1.34, 7.42, 6.97, 4.55]

For any one member of the list, I know I can format it by using

print "%.2f" % member

Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.

Asked By: Curious2learn

||

Answers:

If you just want to print the numbers you can use a simple loop:

for member in theList:
    print "%.2f" % member

If you want to store the result for later you can use a list comprehension:

formattedList = ["%.2f" % member for member in theList]

You can then print this list to get the output as in your question:

print formattedList

Note also that % is being deprecated. If you are using Python 2.6 or newer prefer to use format.

Answered By: Mark Byers

You can use list comprehension, join and some string manipulation, as follows:

>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> def format(l):
...     return "["+", ".join(["%.2f" % x for x in l])+"]"
... 
>>> format(theList)
'[1.34, 7.42, 6.97, 4.55]'
Answered By: moshez

You can use the map function

l2 = map(lambda n: "%.2f" % n, l)
Answered By: jbochi

For Python 3.5.1, you can use:

>>> theList = [1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> strFormat = len(theList) * '{:10f} '
>>> formattedList = strFormat.format(*theList)
>>> print(formattedList)

The result is:

'  1.343465   7.423334   6.967998   4.552258 '
Answered By: rvcristiand

A very short solution using “”.format() and a generator expression:

>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

>>> print(['{:.2f}'.format(item) for item in theList])

['1.34', '7.42', '6.97', '4.55']
Answered By: rauschi2000

Try this one if you don’t need to save your values:

list = [0.34555, 0.2323456, 0.6234232, 0.45234234]
for member in list:
    form='{:.1%}'.format(member)
    print(form)

output:

34.6%
23.2%
62.3%
45.2%
Answered By: Flo Rem

You can use helper function:

def format_list(a, fmt, sep=', ', start='[', end=']'):
    return start + sep.join([format(x, fmt) for x in a]) + end

usage:

a=[4,8,15,16,23,42]

print(f"%d is {format_list(a, 'd')} %x is {format_list(a, 'x')} %b is {format_list(a, 'b')}")
Answered By: quant2016