Python - list transformation

I would use a list comprehension myself, but here is another solution using map for those interested...

map(lambda v: "%02d" %v, x)

You can use a list comprehension (Python 2.6+):

y = ["{0:0>2}".format(v) for v in x]

Or for Python prior to 2.6:

y = ["%02d" % v for v in x]

Or for Python 3.6+ using f-strings:

y = [f'{v:02}' for v in x] 

Edit: Missed the fact that you wanted zero-padding...


You want to use the built-in map function:

>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']

EDIT You changed the requirements on me! To make it display leading zeros, you do this:

>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11'] 

Tags:

Python

List