Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Last active October 13, 2018 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/2fb2ebad7ec6881369dcca74e8993422 to your computer and use it in GitHub Desktop.
Save jpluimers/2fb2ebad7ec6881369dcca74e8993422 to your computer and use it in GitHub Desktop.
Python list transformations showing various aspects of the Python 2 and 3 language evolvements
# Links the documentation are Python 2, though everything works in Python 3 as well.
x = [1,2,3,4,5,11]
print("x: ", repr(x))
y = ['01','02','03','04','05','11']
print("y: ", repr(y))
# List comprehension https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
# ... using `str.format()` (Python >= 2.6): https://docs.python.org/2/library/stdtypes.html#str.format and https://docs.python.org/2/library/string.html#formatstrings
y = ["{0:0>2}".format(v) for v in x]
print("y: ", repr(y))
# ... using the traditional `%` formatting operator (Python < 2.6): https://docs.python.org/2/library/stdtypes.html#string-formatting
y = ["%02d" % v for v in x]
print("y: ", repr(y))
# ... using the format()` function (Python >= 2.6): https://docs.python.org/2/library/functions.html#format and https://docs.python.org/2/library/string.html#formatstrings
# this omits the "{0:...}" ceremony from the positional #0 parameter
y = [format(v, "0>2") for v in x]
print("y: ", repr(y))
# Note that for new style format strings, the positional argument (to specify argument #0) is optional (Python >= 2.7) https://docs.python.org/2/library/string.html#formatstrings
y = ["{:0>2}".format(v) for v in x]
print("y: ", repr(y))
# Using `lambda`
# ... Python < 3 return a list
y = map(lambda v: "%02d" %v, x)
print("y: ", repr(y))
# ... Python >= 3 return a map object to iterate over https://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x/1303354#1303354
y = list(map(lambda v: "%02d" %v, x))
print("y: ", repr(y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment